Bump version to 19.1.2
[llvm-project.git] / flang / lib / Lower / ConvertExpr.cpp
blob44c3dc88edd32ff713d8e294bb5cd5916a1d2430
1 //===-- ConvertExpr.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 // Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/
11 //===----------------------------------------------------------------------===//
13 #include "flang/Lower/ConvertExpr.h"
14 #include "flang/Common/default-kinds.h"
15 #include "flang/Common/unwrap.h"
16 #include "flang/Evaluate/fold.h"
17 #include "flang/Evaluate/real.h"
18 #include "flang/Evaluate/traverse.h"
19 #include "flang/Lower/Allocatable.h"
20 #include "flang/Lower/Bridge.h"
21 #include "flang/Lower/BuiltinModules.h"
22 #include "flang/Lower/CallInterface.h"
23 #include "flang/Lower/Coarray.h"
24 #include "flang/Lower/ComponentPath.h"
25 #include "flang/Lower/ConvertCall.h"
26 #include "flang/Lower/ConvertConstant.h"
27 #include "flang/Lower/ConvertProcedureDesignator.h"
28 #include "flang/Lower/ConvertType.h"
29 #include "flang/Lower/ConvertVariable.h"
30 #include "flang/Lower/CustomIntrinsicCall.h"
31 #include "flang/Lower/DumpEvaluateExpr.h"
32 #include "flang/Lower/Mangler.h"
33 #include "flang/Lower/Runtime.h"
34 #include "flang/Lower/Support/Utils.h"
35 #include "flang/Optimizer/Builder/Character.h"
36 #include "flang/Optimizer/Builder/Complex.h"
37 #include "flang/Optimizer/Builder/Factory.h"
38 #include "flang/Optimizer/Builder/IntrinsicCall.h"
39 #include "flang/Optimizer/Builder/Runtime/Assign.h"
40 #include "flang/Optimizer/Builder/Runtime/Character.h"
41 #include "flang/Optimizer/Builder/Runtime/Derived.h"
42 #include "flang/Optimizer/Builder/Runtime/Inquiry.h"
43 #include "flang/Optimizer/Builder/Runtime/RTBuilder.h"
44 #include "flang/Optimizer/Builder/Runtime/Ragged.h"
45 #include "flang/Optimizer/Builder/Todo.h"
46 #include "flang/Optimizer/Dialect/FIRAttr.h"
47 #include "flang/Optimizer/Dialect/FIRDialect.h"
48 #include "flang/Optimizer/Dialect/FIROpsSupport.h"
49 #include "flang/Optimizer/Support/FatalError.h"
50 #include "flang/Runtime/support.h"
51 #include "flang/Semantics/expression.h"
52 #include "flang/Semantics/symbol.h"
53 #include "flang/Semantics/tools.h"
54 #include "flang/Semantics/type.h"
55 #include "mlir/Dialect/Func/IR/FuncOps.h"
56 #include "llvm/ADT/TypeSwitch.h"
57 #include "llvm/Support/CommandLine.h"
58 #include "llvm/Support/Debug.h"
59 #include "llvm/Support/ErrorHandling.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include <algorithm>
62 #include <optional>
64 #define DEBUG_TYPE "flang-lower-expr"
66 using namespace Fortran::runtime;
68 //===----------------------------------------------------------------------===//
69 // The composition and structure of Fortran::evaluate::Expr is defined in
70 // the various header files in include/flang/Evaluate. You are referred
71 // there for more information on these data structures. Generally speaking,
72 // these data structures are a strongly typed family of abstract data types
73 // that, composed as trees, describe the syntax of Fortran expressions.
75 // This part of the bridge can traverse these tree structures and lower them
76 // to the correct FIR representation in SSA form.
77 //===----------------------------------------------------------------------===//
79 static llvm::cl::opt<bool> generateArrayCoordinate(
80 "gen-array-coor",
81 llvm::cl::desc("in lowering create ArrayCoorOp instead of CoordinateOp"),
82 llvm::cl::init(false));
84 // The default attempts to balance a modest allocation size with expected user
85 // input to minimize bounds checks and reallocations during dynamic array
86 // construction. Some user codes may have very large array constructors for
87 // which the default can be increased.
88 static llvm::cl::opt<unsigned> clInitialBufferSize(
89 "array-constructor-initial-buffer-size",
90 llvm::cl::desc(
91 "set the incremental array construction buffer size (default=32)"),
92 llvm::cl::init(32u));
94 // Lower TRANSPOSE as an "elemental" function that swaps the array
95 // expression's iteration space, so that no runtime call is needed.
96 // This lowering may help get rid of unnecessary creation of temporary
97 // arrays. Note that the runtime TRANSPOSE implementation may be different
98 // from the "inline" FIR, e.g. it may diagnose out-of-memory conditions
99 // during the temporary allocation whereas the inline implementation
100 // relies on AllocMemOp that will silently return null in case
101 // there is not enough memory.
103 // If it is set to false, then TRANSPOSE will be lowered using
104 // a runtime call. If it is set to true, then the lowering is controlled
105 // by LoweringOptions::optimizeTranspose bit (see isTransposeOptEnabled
106 // function in this file).
107 static llvm::cl::opt<bool> optimizeTranspose(
108 "opt-transpose",
109 llvm::cl::desc("lower transpose without using a runtime call"),
110 llvm::cl::init(true));
112 // When copy-in/copy-out is generated for a boxed object we may
113 // either produce loops to copy the data or call the Fortran runtime's
114 // Assign function. Since the data copy happens under a runtime check
115 // (for IsContiguous) the copy loops can hardly provide any value
116 // to optimizations, instead, the optimizer just wastes compilation
117 // time on these loops.
119 // This internal option will force the loops generation, when set
120 // to true. It is false by default.
122 // Note that for copy-in/copy-out of non-boxed objects (e.g. for passing
123 // arguments by value) we always generate loops. Since the memory for
124 // such objects is contiguous, it may be better to expose them
125 // to the optimizer.
126 static llvm::cl::opt<bool> inlineCopyInOutForBoxes(
127 "inline-copyinout-for-boxes",
128 llvm::cl::desc(
129 "generate loops for copy-in/copy-out of objects with descriptors"),
130 llvm::cl::init(false));
132 /// The various semantics of a program constituent (or a part thereof) as it may
133 /// appear in an expression.
135 /// Given the following Fortran declarations.
136 /// ```fortran
137 /// REAL :: v1, v2, v3
138 /// REAL, POINTER :: vp1
139 /// REAL :: a1(c), a2(c)
140 /// REAL ELEMENTAL FUNCTION f1(arg) ! array -> array
141 /// FUNCTION f2(arg) ! array -> array
142 /// vp1 => v3 ! 1
143 /// v1 = v2 * vp1 ! 2
144 /// a1 = a1 + a2 ! 3
145 /// a1 = f1(a2) ! 4
146 /// a1 = f2(a2) ! 5
147 /// ```
149 /// In line 1, `vp1` is a BoxAddr to copy a box value into. The box value is
150 /// constructed from the DataAddr of `v3`.
151 /// In line 2, `v1` is a DataAddr to copy a value into. The value is constructed
152 /// from the DataValue of `v2` and `vp1`. DataValue is implicitly a double
153 /// dereference in the `vp1` case.
154 /// In line 3, `a1` and `a2` on the rhs are RefTransparent. The `a1` on the lhs
155 /// is CopyInCopyOut as `a1` is replaced elementally by the additions.
156 /// In line 4, `a2` can be RefTransparent, ByValueArg, RefOpaque, or BoxAddr if
157 /// `arg` is declared as C-like pass-by-value, VALUE, INTENT(?), or ALLOCATABLE/
158 /// POINTER, respectively. `a1` on the lhs is CopyInCopyOut.
159 /// In line 5, `a2` may be DataAddr or BoxAddr assuming f2 is transformational.
160 /// `a1` on the lhs is again CopyInCopyOut.
161 enum class ConstituentSemantics {
162 // Scalar data reference semantics.
164 // For these let `v` be the location in memory of a variable with value `x`
165 DataValue, // refers to the value `x`
166 DataAddr, // refers to the address `v`
167 BoxValue, // refers to a box value containing `v`
168 BoxAddr, // refers to the address of a box value containing `v`
170 // Array data reference semantics.
172 // For these let `a` be the location in memory of a sequence of value `[xs]`.
173 // Let `x_i` be the `i`-th value in the sequence `[xs]`.
175 // Referentially transparent. Refers to the array's value, `[xs]`.
176 RefTransparent,
177 // Refers to an ephemeral address `tmp` containing value `x_i` (15.5.2.3.p7
178 // note 2). (Passing a copy by reference to simulate pass-by-value.)
179 ByValueArg,
180 // Refers to the merge of array value `[xs]` with another array value `[ys]`.
181 // This merged array value will be written into memory location `a`.
182 CopyInCopyOut,
183 // Similar to CopyInCopyOut but `a` may be a transient projection (rather than
184 // a whole array).
185 ProjectedCopyInCopyOut,
186 // Similar to ProjectedCopyInCopyOut, except the merge value is not assigned
187 // automatically by the framework. Instead, and address for `[xs]` is made
188 // accessible so that custom assignments to `[xs]` can be implemented.
189 CustomCopyInCopyOut,
190 // Referentially opaque. Refers to the address of `x_i`.
191 RefOpaque
194 /// Convert parser's INTEGER relational operators to MLIR. TODO: using
195 /// unordered, but we may want to cons ordered in certain situation.
196 static mlir::arith::CmpIPredicate
197 translateRelational(Fortran::common::RelationalOperator rop) {
198 switch (rop) {
199 case Fortran::common::RelationalOperator::LT:
200 return mlir::arith::CmpIPredicate::slt;
201 case Fortran::common::RelationalOperator::LE:
202 return mlir::arith::CmpIPredicate::sle;
203 case Fortran::common::RelationalOperator::EQ:
204 return mlir::arith::CmpIPredicate::eq;
205 case Fortran::common::RelationalOperator::NE:
206 return mlir::arith::CmpIPredicate::ne;
207 case Fortran::common::RelationalOperator::GT:
208 return mlir::arith::CmpIPredicate::sgt;
209 case Fortran::common::RelationalOperator::GE:
210 return mlir::arith::CmpIPredicate::sge;
212 llvm_unreachable("unhandled INTEGER relational operator");
215 /// Convert parser's REAL relational operators to MLIR.
216 /// The choice of order (O prefix) vs unorder (U prefix) follows Fortran 2018
217 /// requirements in the IEEE context (table 17.1 of F2018). This choice is
218 /// also applied in other contexts because it is easier and in line with
219 /// other Fortran compilers.
220 /// FIXME: The signaling/quiet aspect of the table 17.1 requirement is not
221 /// fully enforced. FIR and LLVM `fcmp` instructions do not give any guarantee
222 /// whether the comparison will signal or not in case of quiet NaN argument.
223 static mlir::arith::CmpFPredicate
224 translateFloatRelational(Fortran::common::RelationalOperator rop) {
225 switch (rop) {
226 case Fortran::common::RelationalOperator::LT:
227 return mlir::arith::CmpFPredicate::OLT;
228 case Fortran::common::RelationalOperator::LE:
229 return mlir::arith::CmpFPredicate::OLE;
230 case Fortran::common::RelationalOperator::EQ:
231 return mlir::arith::CmpFPredicate::OEQ;
232 case Fortran::common::RelationalOperator::NE:
233 return mlir::arith::CmpFPredicate::UNE;
234 case Fortran::common::RelationalOperator::GT:
235 return mlir::arith::CmpFPredicate::OGT;
236 case Fortran::common::RelationalOperator::GE:
237 return mlir::arith::CmpFPredicate::OGE;
239 llvm_unreachable("unhandled REAL relational operator");
242 static mlir::Value genActualIsPresentTest(fir::FirOpBuilder &builder,
243 mlir::Location loc,
244 fir::ExtendedValue actual) {
245 if (const auto *ptrOrAlloc = actual.getBoxOf<fir::MutableBoxValue>())
246 return fir::factory::genIsAllocatedOrAssociatedTest(builder, loc,
247 *ptrOrAlloc);
248 // Optional case (not that optional allocatable/pointer cannot be absent
249 // when passed to CMPLX as per 15.5.2.12 point 3 (7) and (8)). It is
250 // therefore possible to catch them in the `then` case above.
251 return builder.create<fir::IsPresentOp>(loc, builder.getI1Type(),
252 fir::getBase(actual));
255 /// Convert the array_load, `load`, to an extended value. If `path` is not
256 /// empty, then traverse through the components designated. The base value is
257 /// `newBase`. This does not accept an array_load with a slice operand.
258 static fir::ExtendedValue
259 arrayLoadExtValue(fir::FirOpBuilder &builder, mlir::Location loc,
260 fir::ArrayLoadOp load, llvm::ArrayRef<mlir::Value> path,
261 mlir::Value newBase, mlir::Value newLen = {}) {
262 // Recover the extended value from the load.
263 if (load.getSlice())
264 fir::emitFatalError(loc, "array_load with slice is not allowed");
265 mlir::Type arrTy = load.getType();
266 if (!path.empty()) {
267 mlir::Type ty = fir::applyPathToType(arrTy, path);
268 if (!ty)
269 fir::emitFatalError(loc, "path does not apply to type");
270 if (!mlir::isa<fir::SequenceType>(ty)) {
271 if (fir::isa_char(ty)) {
272 mlir::Value len = newLen;
273 if (!len)
274 len = fir::factory::CharacterExprHelper{builder, loc}.getLength(
275 load.getMemref());
276 if (!len) {
277 assert(load.getTypeparams().size() == 1 &&
278 "length must be in array_load");
279 len = load.getTypeparams()[0];
281 return fir::CharBoxValue{newBase, len};
283 return newBase;
285 arrTy = mlir::cast<fir::SequenceType>(ty);
288 auto arrayToExtendedValue =
289 [&](const llvm::SmallVector<mlir::Value> &extents,
290 const llvm::SmallVector<mlir::Value> &origins) -> fir::ExtendedValue {
291 mlir::Type eleTy = fir::unwrapSequenceType(arrTy);
292 if (fir::isa_char(eleTy)) {
293 mlir::Value len = newLen;
294 if (!len)
295 len = fir::factory::CharacterExprHelper{builder, loc}.getLength(
296 load.getMemref());
297 if (!len) {
298 assert(load.getTypeparams().size() == 1 &&
299 "length must be in array_load");
300 len = load.getTypeparams()[0];
302 return fir::CharArrayBoxValue(newBase, len, extents, origins);
304 return fir::ArrayBoxValue(newBase, extents, origins);
306 // Use the shape op, if there is one.
307 mlir::Value shapeVal = load.getShape();
308 if (shapeVal) {
309 if (!mlir::isa<fir::ShiftOp>(shapeVal.getDefiningOp())) {
310 auto extents = fir::factory::getExtents(shapeVal);
311 auto origins = fir::factory::getOrigins(shapeVal);
312 return arrayToExtendedValue(extents, origins);
314 if (!fir::isa_box_type(load.getMemref().getType()))
315 fir::emitFatalError(loc, "shift op is invalid in this context");
318 // If we're dealing with the array_load op (not a subobject) and the load does
319 // not have any type parameters, then read the extents from the original box.
320 // The origin may be either from the box or a shift operation. Create and
321 // return the array extended value.
322 if (path.empty() && load.getTypeparams().empty()) {
323 auto oldBox = load.getMemref();
324 fir::ExtendedValue exv = fir::factory::readBoxValue(builder, loc, oldBox);
325 auto extents = fir::factory::getExtents(loc, builder, exv);
326 auto origins = fir::factory::getNonDefaultLowerBounds(builder, loc, exv);
327 if (shapeVal) {
328 // shapeVal is a ShiftOp and load.memref() is a boxed value.
329 newBase = builder.create<fir::ReboxOp>(loc, oldBox.getType(), oldBox,
330 shapeVal, /*slice=*/mlir::Value{});
331 origins = fir::factory::getOrigins(shapeVal);
333 return fir::substBase(arrayToExtendedValue(extents, origins), newBase);
335 TODO(loc, "path to a POINTER, ALLOCATABLE, or other component that requires "
336 "dereferencing; generating the type parameters is a hard "
337 "requirement for correctness.");
340 /// Place \p exv in memory if it is not already a memory reference. If
341 /// \p forceValueType is provided, the value is first casted to the provided
342 /// type before being stored (this is mainly intended for logicals whose value
343 /// may be `i1` but needed to be stored as Fortran logicals).
344 static fir::ExtendedValue
345 placeScalarValueInMemory(fir::FirOpBuilder &builder, mlir::Location loc,
346 const fir::ExtendedValue &exv,
347 mlir::Type storageType) {
348 mlir::Value valBase = fir::getBase(exv);
349 if (fir::conformsWithPassByRef(valBase.getType()))
350 return exv;
352 assert(!fir::hasDynamicSize(storageType) &&
353 "only expect statically sized scalars to be by value");
355 // Since `a` is not itself a valid referent, determine its value and
356 // create a temporary location at the beginning of the function for
357 // referencing.
358 mlir::Value val = builder.createConvert(loc, storageType, valBase);
359 mlir::Value temp = builder.createTemporary(
360 loc, storageType,
361 llvm::ArrayRef<mlir::NamedAttribute>{fir::getAdaptToByRefAttr(builder)});
362 builder.create<fir::StoreOp>(loc, val, temp);
363 return fir::substBase(exv, temp);
366 // Copy a copy of scalar \p exv in a new temporary.
367 static fir::ExtendedValue
368 createInMemoryScalarCopy(fir::FirOpBuilder &builder, mlir::Location loc,
369 const fir::ExtendedValue &exv) {
370 assert(exv.rank() == 0 && "input to scalar memory copy must be a scalar");
371 if (exv.getCharBox() != nullptr)
372 return fir::factory::CharacterExprHelper{builder, loc}.createTempFrom(exv);
373 if (fir::isDerivedWithLenParameters(exv))
374 TODO(loc, "copy derived type with length parameters");
375 mlir::Type type = fir::unwrapPassByRefType(fir::getBase(exv).getType());
376 fir::ExtendedValue temp = builder.createTemporary(loc, type);
377 fir::factory::genScalarAssignment(builder, loc, temp, exv);
378 return temp;
381 // An expression with non-zero rank is an array expression.
382 template <typename A>
383 static bool isArray(const A &x) {
384 return x.Rank() != 0;
387 /// Is this a variable wrapped in parentheses?
388 template <typename A>
389 static bool isParenthesizedVariable(const A &) {
390 return false;
392 template <typename T>
393 static bool isParenthesizedVariable(const Fortran::evaluate::Expr<T> &expr) {
394 using ExprVariant = decltype(Fortran::evaluate::Expr<T>::u);
395 using Parentheses = Fortran::evaluate::Parentheses<T>;
396 if constexpr (Fortran::common::HasMember<Parentheses, ExprVariant>) {
397 if (const auto *parentheses = std::get_if<Parentheses>(&expr.u))
398 return Fortran::evaluate::IsVariable(parentheses->left());
399 return false;
400 } else {
401 return Fortran::common::visit(
402 [&](const auto &x) { return isParenthesizedVariable(x); }, expr.u);
406 /// Generate a load of a value from an address. Beware that this will lose
407 /// any dynamic type information for polymorphic entities (note that unlimited
408 /// polymorphic cannot be loaded and must not be provided here).
409 static fir::ExtendedValue genLoad(fir::FirOpBuilder &builder,
410 mlir::Location loc,
411 const fir::ExtendedValue &addr) {
412 return addr.match(
413 [](const fir::CharBoxValue &box) -> fir::ExtendedValue { return box; },
414 [&](const fir::PolymorphicValue &p) -> fir::ExtendedValue {
415 if (mlir::isa<fir::RecordType>(
416 fir::unwrapRefType(fir::getBase(p).getType())))
417 return p;
418 mlir::Value load = builder.create<fir::LoadOp>(loc, fir::getBase(p));
419 return fir::PolymorphicValue(load, p.getSourceBox());
421 [&](const fir::UnboxedValue &v) -> fir::ExtendedValue {
422 if (mlir::isa<fir::RecordType>(
423 fir::unwrapRefType(fir::getBase(v).getType())))
424 return v;
425 return builder.create<fir::LoadOp>(loc, fir::getBase(v));
427 [&](const fir::MutableBoxValue &box) -> fir::ExtendedValue {
428 return genLoad(builder, loc,
429 fir::factory::genMutableBoxRead(builder, loc, box));
431 [&](const fir::BoxValue &box) -> fir::ExtendedValue {
432 return genLoad(builder, loc,
433 fir::factory::readBoxValue(builder, loc, box));
435 [&](const auto &) -> fir::ExtendedValue {
436 fir::emitFatalError(
437 loc, "attempting to load whole array or procedure address");
441 /// Create an optional dummy argument value from entity \p exv that may be
442 /// absent. This can only be called with numerical or logical scalar \p exv.
443 /// If \p exv is considered absent according to 15.5.2.12 point 1., the returned
444 /// value is zero (or false), otherwise it is the value of \p exv.
445 static fir::ExtendedValue genOptionalValue(fir::FirOpBuilder &builder,
446 mlir::Location loc,
447 const fir::ExtendedValue &exv,
448 mlir::Value isPresent) {
449 mlir::Type eleType = fir::getBaseTypeOf(exv);
450 assert(exv.rank() == 0 && fir::isa_trivial(eleType) &&
451 "must be a numerical or logical scalar");
452 return builder
453 .genIfOp(loc, {eleType}, isPresent,
454 /*withElseRegion=*/true)
455 .genThen([&]() {
456 mlir::Value val = fir::getBase(genLoad(builder, loc, exv));
457 builder.create<fir::ResultOp>(loc, val);
459 .genElse([&]() {
460 mlir::Value zero = fir::factory::createZeroValue(builder, loc, eleType);
461 builder.create<fir::ResultOp>(loc, zero);
463 .getResults()[0];
466 /// Create an optional dummy argument address from entity \p exv that may be
467 /// absent. If \p exv is considered absent according to 15.5.2.12 point 1., the
468 /// returned value is a null pointer, otherwise it is the address of \p exv.
469 static fir::ExtendedValue genOptionalAddr(fir::FirOpBuilder &builder,
470 mlir::Location loc,
471 const fir::ExtendedValue &exv,
472 mlir::Value isPresent) {
473 // If it is an exv pointer/allocatable, then it cannot be absent
474 // because it is passed to a non-pointer/non-allocatable.
475 if (const auto *box = exv.getBoxOf<fir::MutableBoxValue>())
476 return fir::factory::genMutableBoxRead(builder, loc, *box);
477 // If this is not a POINTER or ALLOCATABLE, then it is already an OPTIONAL
478 // address and can be passed directly.
479 return exv;
482 /// Create an optional dummy argument address from entity \p exv that may be
483 /// absent. If \p exv is considered absent according to 15.5.2.12 point 1., the
484 /// returned value is an absent fir.box, otherwise it is a fir.box describing \p
485 /// exv.
486 static fir::ExtendedValue genOptionalBox(fir::FirOpBuilder &builder,
487 mlir::Location loc,
488 const fir::ExtendedValue &exv,
489 mlir::Value isPresent) {
490 // Non allocatable/pointer optional box -> simply forward
491 if (exv.getBoxOf<fir::BoxValue>())
492 return exv;
494 fir::ExtendedValue newExv = exv;
495 // Optional allocatable/pointer -> Cannot be absent, but need to translate
496 // unallocated/diassociated into absent fir.box.
497 if (const auto *box = exv.getBoxOf<fir::MutableBoxValue>())
498 newExv = fir::factory::genMutableBoxRead(builder, loc, *box);
500 // createBox will not do create any invalid memory dereferences if exv is
501 // absent. The created fir.box will not be usable, but the SelectOp below
502 // ensures it won't be.
503 mlir::Value box = builder.createBox(loc, newExv);
504 mlir::Type boxType = box.getType();
505 auto absent = builder.create<fir::AbsentOp>(loc, boxType);
506 auto boxOrAbsent = builder.create<mlir::arith::SelectOp>(
507 loc, boxType, isPresent, box, absent);
508 return fir::BoxValue(boxOrAbsent);
511 /// Is this a call to an elemental procedure with at least one array argument?
512 static bool
513 isElementalProcWithArrayArgs(const Fortran::evaluate::ProcedureRef &procRef) {
514 if (procRef.IsElemental())
515 for (const std::optional<Fortran::evaluate::ActualArgument> &arg :
516 procRef.arguments())
517 if (arg && arg->Rank() != 0)
518 return true;
519 return false;
521 template <typename T>
522 static bool isElementalProcWithArrayArgs(const Fortran::evaluate::Expr<T> &) {
523 return false;
525 template <>
526 bool isElementalProcWithArrayArgs(const Fortran::lower::SomeExpr &x) {
527 if (const auto *procRef = std::get_if<Fortran::evaluate::ProcedureRef>(&x.u))
528 return isElementalProcWithArrayArgs(*procRef);
529 return false;
532 /// \p argTy must be a tuple (pair) of boxproc and integral types. Convert the
533 /// \p funcAddr argument to a boxproc value, with the host-association as
534 /// required. Call the factory function to finish creating the tuple value.
535 static mlir::Value
536 createBoxProcCharTuple(Fortran::lower::AbstractConverter &converter,
537 mlir::Type argTy, mlir::Value funcAddr,
538 mlir::Value charLen) {
539 auto boxTy = mlir::cast<fir::BoxProcType>(
540 mlir::cast<mlir::TupleType>(argTy).getType(0));
541 mlir::Location loc = converter.getCurrentLocation();
542 auto &builder = converter.getFirOpBuilder();
544 // While character procedure arguments are expected here, Fortran allows
545 // actual arguments of other types to be passed instead.
546 // To support this, we cast any reference to the expected type or extract
547 // procedures from their boxes if needed.
548 mlir::Type fromTy = funcAddr.getType();
549 mlir::Type toTy = boxTy.getEleTy();
550 if (fir::isa_ref_type(fromTy))
551 funcAddr = builder.createConvert(loc, toTy, funcAddr);
552 else if (mlir::isa<fir::BoxProcType>(fromTy))
553 funcAddr = builder.create<fir::BoxAddrOp>(loc, toTy, funcAddr);
555 auto boxProc = [&]() -> mlir::Value {
556 if (auto host = Fortran::lower::argumentHostAssocs(converter, funcAddr))
557 return builder.create<fir::EmboxProcOp>(
558 loc, boxTy, llvm::ArrayRef<mlir::Value>{funcAddr, host});
559 return builder.create<fir::EmboxProcOp>(loc, boxTy, funcAddr);
560 }();
561 return fir::factory::createCharacterProcedureTuple(builder, loc, argTy,
562 boxProc, charLen);
565 /// Given an optional fir.box, returns an fir.box that is the original one if
566 /// it is present and it otherwise an unallocated box.
567 /// Absent fir.box are implemented as a null pointer descriptor. Generated
568 /// code may need to unconditionally read a fir.box that can be absent.
569 /// This helper allows creating a fir.box that can be read in all cases
570 /// outside of a fir.if (isPresent) region. However, the usages of the value
571 /// read from such box should still only be done in a fir.if(isPresent).
572 static fir::ExtendedValue
573 absentBoxToUnallocatedBox(fir::FirOpBuilder &builder, mlir::Location loc,
574 const fir::ExtendedValue &exv,
575 mlir::Value isPresent) {
576 mlir::Value box = fir::getBase(exv);
577 mlir::Type boxType = box.getType();
578 assert(mlir::isa<fir::BoxType>(boxType) && "argument must be a fir.box");
579 mlir::Value emptyBox =
580 fir::factory::createUnallocatedBox(builder, loc, boxType, std::nullopt);
581 auto safeToReadBox =
582 builder.create<mlir::arith::SelectOp>(loc, isPresent, box, emptyBox);
583 return fir::substBase(exv, safeToReadBox);
586 // Helper to get the ultimate first symbol. This works around the fact that
587 // symbol resolution in the front end doesn't always resolve a symbol to its
588 // ultimate symbol but may leave placeholder indirections for use and host
589 // associations.
590 template <typename A>
591 const Fortran::semantics::Symbol &getFirstSym(const A &obj) {
592 const Fortran::semantics::Symbol &sym = obj.GetFirstSymbol();
593 return sym.HasLocalLocality() ? sym : sym.GetUltimate();
596 // Helper to get the ultimate last symbol.
597 template <typename A>
598 const Fortran::semantics::Symbol &getLastSym(const A &obj) {
599 const Fortran::semantics::Symbol &sym = obj.GetLastSymbol();
600 return sym.HasLocalLocality() ? sym : sym.GetUltimate();
603 // Return true if TRANSPOSE should be lowered without a runtime call.
604 static bool
605 isTransposeOptEnabled(const Fortran::lower::AbstractConverter &converter) {
606 return optimizeTranspose &&
607 converter.getLoweringOptions().getOptimizeTranspose();
610 // A set of visitors to detect if the given expression
611 // is a TRANSPOSE call that should be lowered without using
612 // runtime TRANSPOSE implementation.
613 template <typename T>
614 static bool isOptimizableTranspose(const T &,
615 const Fortran::lower::AbstractConverter &) {
616 return false;
619 static bool
620 isOptimizableTranspose(const Fortran::evaluate::ProcedureRef &procRef,
621 const Fortran::lower::AbstractConverter &converter) {
622 const Fortran::evaluate::SpecificIntrinsic *intrin =
623 procRef.proc().GetSpecificIntrinsic();
624 if (isTransposeOptEnabled(converter) && intrin &&
625 intrin->name == "transpose") {
626 const std::optional<Fortran::evaluate::ActualArgument> matrix =
627 procRef.arguments().at(0);
628 return !(matrix && matrix->GetType() && matrix->GetType()->IsPolymorphic());
630 return false;
633 template <typename T>
634 static bool
635 isOptimizableTranspose(const Fortran::evaluate::FunctionRef<T> &funcRef,
636 const Fortran::lower::AbstractConverter &converter) {
637 return isOptimizableTranspose(
638 static_cast<const Fortran::evaluate::ProcedureRef &>(funcRef), converter);
641 template <typename T>
642 static bool
643 isOptimizableTranspose(Fortran::evaluate::Expr<T> expr,
644 const Fortran::lower::AbstractConverter &converter) {
645 // If optimizeTranspose is not enabled, return false right away.
646 if (!isTransposeOptEnabled(converter))
647 return false;
649 return Fortran::common::visit(
650 [&](const auto &e) { return isOptimizableTranspose(e, converter); },
651 expr.u);
654 namespace {
656 /// Lowering of Fortran::evaluate::Expr<T> expressions
657 class ScalarExprLowering {
658 public:
659 using ExtValue = fir::ExtendedValue;
661 explicit ScalarExprLowering(mlir::Location loc,
662 Fortran::lower::AbstractConverter &converter,
663 Fortran::lower::SymMap &symMap,
664 Fortran::lower::StatementContext &stmtCtx,
665 bool inInitializer = false)
666 : location{loc}, converter{converter},
667 builder{converter.getFirOpBuilder()}, stmtCtx{stmtCtx}, symMap{symMap},
668 inInitializer{inInitializer} {}
670 ExtValue genExtAddr(const Fortran::lower::SomeExpr &expr) {
671 return gen(expr);
674 /// Lower `expr` to be passed as a fir.box argument. Do not create a temp
675 /// for the expr if it is a variable that can be described as a fir.box.
676 ExtValue genBoxArg(const Fortran::lower::SomeExpr &expr) {
677 bool saveUseBoxArg = useBoxArg;
678 useBoxArg = true;
679 ExtValue result = gen(expr);
680 useBoxArg = saveUseBoxArg;
681 return result;
684 ExtValue genExtValue(const Fortran::lower::SomeExpr &expr) {
685 return genval(expr);
688 /// Lower an expression that is a pointer or an allocatable to a
689 /// MutableBoxValue.
690 fir::MutableBoxValue
691 genMutableBoxValue(const Fortran::lower::SomeExpr &expr) {
692 // Pointers and allocatables can only be:
693 // - a simple designator "x"
694 // - a component designator "a%b(i,j)%x"
695 // - a function reference "foo()"
696 // - result of NULL() or NULL(MOLD) intrinsic.
697 // NULL() requires some context to be lowered, so it is not handled
698 // here and must be lowered according to the context where it appears.
699 ExtValue exv = Fortran::common::visit(
700 [&](const auto &x) { return genMutableBoxValueImpl(x); }, expr.u);
701 const fir::MutableBoxValue *mutableBox =
702 exv.getBoxOf<fir::MutableBoxValue>();
703 if (!mutableBox)
704 fir::emitFatalError(getLoc(), "expr was not lowered to MutableBoxValue");
705 return *mutableBox;
708 template <typename T>
709 ExtValue genMutableBoxValueImpl(const T &) {
710 // NULL() case should not be handled here.
711 fir::emitFatalError(getLoc(), "NULL() must be lowered in its context");
714 /// A `NULL()` in a position where a mutable box is expected has the same
715 /// semantics as an absent optional box value. Note: this code should
716 /// be depreciated because the rank information is not known here. A
717 /// scalar fir.box is created: it should not be cast to an array box type
718 /// later, but there is no way to enforce that here.
719 ExtValue genMutableBoxValueImpl(const Fortran::evaluate::NullPointer &) {
720 mlir::Location loc = getLoc();
721 mlir::Type noneTy = mlir::NoneType::get(builder.getContext());
722 mlir::Type polyRefTy = fir::PointerType::get(noneTy);
723 mlir::Type boxType = fir::BoxType::get(polyRefTy);
724 mlir::Value tempBox =
725 fir::factory::genNullBoxStorage(builder, loc, boxType);
726 return fir::MutableBoxValue(tempBox,
727 /*lenParameters=*/mlir::ValueRange{},
728 /*mutableProperties=*/{});
731 template <typename T>
732 ExtValue
733 genMutableBoxValueImpl(const Fortran::evaluate::FunctionRef<T> &funRef) {
734 return genRawProcedureRef(funRef, converter.genType(toEvExpr(funRef)));
737 template <typename T>
738 ExtValue
739 genMutableBoxValueImpl(const Fortran::evaluate::Designator<T> &designator) {
740 return Fortran::common::visit(
741 Fortran::common::visitors{
742 [&](const Fortran::evaluate::SymbolRef &sym) -> ExtValue {
743 return converter.getSymbolExtendedValue(*sym, &symMap);
745 [&](const Fortran::evaluate::Component &comp) -> ExtValue {
746 return genComponent(comp);
748 [&](const auto &) -> ExtValue {
749 fir::emitFatalError(getLoc(),
750 "not an allocatable or pointer designator");
752 designator.u);
755 template <typename T>
756 ExtValue genMutableBoxValueImpl(const Fortran::evaluate::Expr<T> &expr) {
757 return Fortran::common::visit(
758 [&](const auto &x) { return genMutableBoxValueImpl(x); }, expr.u);
761 mlir::Location getLoc() { return location; }
763 template <typename A>
764 mlir::Value genunbox(const A &expr) {
765 ExtValue e = genval(expr);
766 if (const fir::UnboxedValue *r = e.getUnboxed())
767 return *r;
768 fir::emitFatalError(getLoc(), "unboxed expression expected");
771 /// Generate an integral constant of `value`
772 template <int KIND>
773 mlir::Value genIntegerConstant(mlir::MLIRContext *context,
774 std::int64_t value) {
775 mlir::Type type =
776 converter.genType(Fortran::common::TypeCategory::Integer, KIND);
777 return builder.createIntegerConstant(getLoc(), type, value);
780 /// Generate a logical/boolean constant of `value`
781 mlir::Value genBoolConstant(bool value) {
782 return builder.createBool(getLoc(), value);
785 mlir::Type getSomeKindInteger() { return builder.getIndexType(); }
787 mlir::func::FuncOp getFunction(llvm::StringRef name,
788 mlir::FunctionType funTy) {
789 if (mlir::func::FuncOp func = builder.getNamedFunction(name))
790 return func;
791 return builder.createFunction(getLoc(), name, funTy);
794 template <typename OpTy>
795 mlir::Value createCompareOp(mlir::arith::CmpIPredicate pred,
796 const ExtValue &left, const ExtValue &right) {
797 if (const fir::UnboxedValue *lhs = left.getUnboxed())
798 if (const fir::UnboxedValue *rhs = right.getUnboxed())
799 return builder.create<OpTy>(getLoc(), pred, *lhs, *rhs);
800 fir::emitFatalError(getLoc(), "array compare should be handled in genarr");
802 template <typename OpTy, typename A>
803 mlir::Value createCompareOp(const A &ex, mlir::arith::CmpIPredicate pred) {
804 ExtValue left = genval(ex.left());
805 return createCompareOp<OpTy>(pred, left, genval(ex.right()));
808 template <typename OpTy>
809 mlir::Value createFltCmpOp(mlir::arith::CmpFPredicate pred,
810 const ExtValue &left, const ExtValue &right) {
811 if (const fir::UnboxedValue *lhs = left.getUnboxed())
812 if (const fir::UnboxedValue *rhs = right.getUnboxed())
813 return builder.create<OpTy>(getLoc(), pred, *lhs, *rhs);
814 fir::emitFatalError(getLoc(), "array compare should be handled in genarr");
816 template <typename OpTy, typename A>
817 mlir::Value createFltCmpOp(const A &ex, mlir::arith::CmpFPredicate pred) {
818 ExtValue left = genval(ex.left());
819 return createFltCmpOp<OpTy>(pred, left, genval(ex.right()));
822 /// Create a call to the runtime to compare two CHARACTER values.
823 /// Precondition: This assumes that the two values have `fir.boxchar` type.
824 mlir::Value createCharCompare(mlir::arith::CmpIPredicate pred,
825 const ExtValue &left, const ExtValue &right) {
826 return fir::runtime::genCharCompare(builder, getLoc(), pred, left, right);
829 template <typename A>
830 mlir::Value createCharCompare(const A &ex, mlir::arith::CmpIPredicate pred) {
831 ExtValue left = genval(ex.left());
832 return createCharCompare(pred, left, genval(ex.right()));
835 /// Returns a reference to a symbol or its box/boxChar descriptor if it has
836 /// one.
837 ExtValue gen(Fortran::semantics::SymbolRef sym) {
838 fir::ExtendedValue exv = converter.getSymbolExtendedValue(sym, &symMap);
839 if (const auto *box = exv.getBoxOf<fir::MutableBoxValue>())
840 return fir::factory::genMutableBoxRead(builder, getLoc(), *box);
841 return exv;
844 ExtValue genLoad(const ExtValue &exv) {
845 return ::genLoad(builder, getLoc(), exv);
848 ExtValue genval(Fortran::semantics::SymbolRef sym) {
849 mlir::Location loc = getLoc();
850 ExtValue var = gen(sym);
851 if (const fir::UnboxedValue *s = var.getUnboxed()) {
852 if (fir::isa_ref_type(s->getType())) {
853 // A function with multiple entry points returning different types
854 // tags all result variables with one of the largest types to allow
855 // them to share the same storage. A reference to a result variable
856 // of one of the other types requires conversion to the actual type.
857 fir::UnboxedValue addr = *s;
858 if (Fortran::semantics::IsFunctionResult(sym)) {
859 mlir::Type resultType = converter.genType(*sym);
860 if (addr.getType() != resultType)
861 addr = builder.createConvert(loc, builder.getRefType(resultType),
862 addr);
863 } else if (sym->test(Fortran::semantics::Symbol::Flag::CrayPointee)) {
864 // get the corresponding Cray pointer
865 Fortran::semantics::SymbolRef ptrSym{
866 Fortran::semantics::GetCrayPointer(sym)};
867 ExtValue ptr = gen(ptrSym);
868 mlir::Value ptrVal = fir::getBase(ptr);
869 mlir::Type ptrTy = converter.genType(*ptrSym);
871 ExtValue pte = gen(sym);
872 mlir::Value pteVal = fir::getBase(pte);
874 mlir::Value cnvrt = Fortran::lower::addCrayPointerInst(
875 loc, builder, ptrVal, ptrTy, pteVal.getType());
876 addr = builder.create<fir::LoadOp>(loc, cnvrt);
878 return genLoad(addr);
881 return var;
884 ExtValue genval(const Fortran::evaluate::BOZLiteralConstant &) {
885 TODO(getLoc(), "BOZ");
888 /// Return indirection to function designated in ProcedureDesignator.
889 /// The type of the function indirection is not guaranteed to match the one
890 /// of the ProcedureDesignator due to Fortran implicit typing rules.
891 ExtValue genval(const Fortran::evaluate::ProcedureDesignator &proc) {
892 return Fortran::lower::convertProcedureDesignator(getLoc(), converter, proc,
893 symMap, stmtCtx);
895 ExtValue genval(const Fortran::evaluate::NullPointer &) {
896 return builder.createNullConstant(getLoc());
899 static bool
900 isDerivedTypeWithLenParameters(const Fortran::semantics::Symbol &sym) {
901 if (const Fortran::semantics::DeclTypeSpec *declTy = sym.GetType())
902 if (const Fortran::semantics::DerivedTypeSpec *derived =
903 declTy->AsDerived())
904 return Fortran::semantics::CountLenParameters(*derived) > 0;
905 return false;
908 /// A structure constructor is lowered two ways. In an initializer context,
909 /// the entire structure must be constant, so the aggregate value is
910 /// constructed inline. This allows it to be the body of a GlobalOp.
911 /// Otherwise, the structure constructor is in an expression. In that case, a
912 /// temporary object is constructed in the stack frame of the procedure.
913 ExtValue genval(const Fortran::evaluate::StructureConstructor &ctor) {
914 mlir::Location loc = getLoc();
915 if (inInitializer)
916 return Fortran::lower::genInlinedStructureCtorLit(converter, loc, ctor);
917 mlir::Type ty = translateSomeExprToFIRType(converter, toEvExpr(ctor));
918 auto recTy = mlir::cast<fir::RecordType>(ty);
919 auto fieldTy = fir::FieldType::get(ty.getContext());
920 mlir::Value res = builder.createTemporary(loc, recTy);
921 mlir::Value box = builder.createBox(loc, fir::ExtendedValue{res});
922 fir::runtime::genDerivedTypeInitialize(builder, loc, box);
924 for (const auto &value : ctor.values()) {
925 const Fortran::semantics::Symbol &sym = *value.first;
926 const Fortran::lower::SomeExpr &expr = value.second.value();
927 if (sym.test(Fortran::semantics::Symbol::Flag::ParentComp)) {
928 ExtValue from = gen(expr);
929 mlir::Type fromTy = fir::unwrapPassByRefType(
930 fir::unwrapRefType(fir::getBase(from).getType()));
931 mlir::Value resCast =
932 builder.createConvert(loc, builder.getRefType(fromTy), res);
933 fir::factory::genRecordAssignment(builder, loc, resCast, from);
934 continue;
937 if (isDerivedTypeWithLenParameters(sym))
938 TODO(loc, "component with length parameters in structure constructor");
940 std::string name = converter.getRecordTypeFieldName(sym);
941 // FIXME: type parameters must come from the derived-type-spec
942 mlir::Value field = builder.create<fir::FieldIndexOp>(
943 loc, fieldTy, name, ty,
944 /*typeParams=*/mlir::ValueRange{} /*TODO*/);
945 mlir::Type coorTy = builder.getRefType(recTy.getType(name));
946 auto coor = builder.create<fir::CoordinateOp>(loc, coorTy,
947 fir::getBase(res), field);
948 ExtValue to = fir::factory::componentToExtendedValue(builder, loc, coor);
949 to.match(
950 [&](const fir::UnboxedValue &toPtr) {
951 ExtValue value = genval(expr);
952 fir::factory::genScalarAssignment(builder, loc, to, value);
954 [&](const fir::CharBoxValue &) {
955 ExtValue value = genval(expr);
956 fir::factory::genScalarAssignment(builder, loc, to, value);
958 [&](const fir::ArrayBoxValue &) {
959 Fortran::lower::createSomeArrayAssignment(converter, to, expr,
960 symMap, stmtCtx);
962 [&](const fir::CharArrayBoxValue &) {
963 Fortran::lower::createSomeArrayAssignment(converter, to, expr,
964 symMap, stmtCtx);
966 [&](const fir::BoxValue &toBox) {
967 fir::emitFatalError(loc, "derived type components must not be "
968 "represented by fir::BoxValue");
970 [&](const fir::PolymorphicValue &) {
971 TODO(loc, "polymorphic component in derived type assignment");
973 [&](const fir::MutableBoxValue &toBox) {
974 if (toBox.isPointer()) {
975 Fortran::lower::associateMutableBox(converter, loc, toBox, expr,
976 /*lbounds=*/std::nullopt,
977 stmtCtx);
978 return;
980 // For allocatable components, a deep copy is needed.
981 TODO(loc, "allocatable components in derived type assignment");
983 [&](const fir::ProcBoxValue &toBox) {
984 TODO(loc, "procedure pointer component in derived type assignment");
987 return res;
990 /// Lowering of an <i>ac-do-variable</i>, which is not a Symbol.
991 ExtValue genval(const Fortran::evaluate::ImpliedDoIndex &var) {
992 mlir::Value value = converter.impliedDoBinding(toStringRef(var.name));
993 // The index value generated by the implied-do has Index type,
994 // while computations based on it inside the loop body are using
995 // the original data type. So we need to cast it appropriately.
996 mlir::Type varTy = converter.genType(toEvExpr(var));
997 return builder.createConvert(getLoc(), varTy, value);
1000 ExtValue genval(const Fortran::evaluate::DescriptorInquiry &desc) {
1001 ExtValue exv = desc.base().IsSymbol() ? gen(getLastSym(desc.base()))
1002 : gen(desc.base().GetComponent());
1003 mlir::IndexType idxTy = builder.getIndexType();
1004 mlir::Location loc = getLoc();
1005 auto castResult = [&](mlir::Value v) {
1006 using ResTy = Fortran::evaluate::DescriptorInquiry::Result;
1007 return builder.createConvert(
1008 loc, converter.genType(ResTy::category, ResTy::kind), v);
1010 switch (desc.field()) {
1011 case Fortran::evaluate::DescriptorInquiry::Field::Len:
1012 return castResult(fir::factory::readCharLen(builder, loc, exv));
1013 case Fortran::evaluate::DescriptorInquiry::Field::LowerBound:
1014 return castResult(fir::factory::readLowerBound(
1015 builder, loc, exv, desc.dimension(),
1016 builder.createIntegerConstant(loc, idxTy, 1)));
1017 case Fortran::evaluate::DescriptorInquiry::Field::Extent:
1018 return castResult(
1019 fir::factory::readExtent(builder, loc, exv, desc.dimension()));
1020 case Fortran::evaluate::DescriptorInquiry::Field::Rank:
1021 TODO(loc, "rank inquiry on assumed rank");
1022 case Fortran::evaluate::DescriptorInquiry::Field::Stride:
1023 // So far the front end does not generate this inquiry.
1024 TODO(loc, "stride inquiry");
1026 llvm_unreachable("unknown descriptor inquiry");
1029 ExtValue genval(const Fortran::evaluate::TypeParamInquiry &) {
1030 TODO(getLoc(), "type parameter inquiry");
1033 mlir::Value extractComplexPart(mlir::Value cplx, bool isImagPart) {
1034 return fir::factory::Complex{builder, getLoc()}.extractComplexPart(
1035 cplx, isImagPart);
1038 template <int KIND>
1039 ExtValue genval(const Fortran::evaluate::ComplexComponent<KIND> &part) {
1040 return extractComplexPart(genunbox(part.left()), part.isImaginaryPart);
1043 template <int KIND>
1044 ExtValue genval(const Fortran::evaluate::Negate<Fortran::evaluate::Type<
1045 Fortran::common::TypeCategory::Integer, KIND>> &op) {
1046 mlir::Value input = genunbox(op.left());
1047 // Like LLVM, integer negation is the binary op "0 - value"
1048 mlir::Value zero = genIntegerConstant<KIND>(builder.getContext(), 0);
1049 return builder.create<mlir::arith::SubIOp>(getLoc(), zero, input);
1051 template <int KIND>
1052 ExtValue genval(const Fortran::evaluate::Negate<Fortran::evaluate::Type<
1053 Fortran::common::TypeCategory::Real, KIND>> &op) {
1054 return builder.create<mlir::arith::NegFOp>(getLoc(), genunbox(op.left()));
1056 template <int KIND>
1057 ExtValue genval(const Fortran::evaluate::Negate<Fortran::evaluate::Type<
1058 Fortran::common::TypeCategory::Complex, KIND>> &op) {
1059 return builder.create<fir::NegcOp>(getLoc(), genunbox(op.left()));
1062 template <typename OpTy>
1063 mlir::Value createBinaryOp(const ExtValue &left, const ExtValue &right) {
1064 assert(fir::isUnboxedValue(left) && fir::isUnboxedValue(right));
1065 mlir::Value lhs = fir::getBase(left);
1066 mlir::Value rhs = fir::getBase(right);
1067 assert(lhs.getType() == rhs.getType() && "types must be the same");
1068 return builder.create<OpTy>(getLoc(), lhs, rhs);
1071 template <typename OpTy, typename A>
1072 mlir::Value createBinaryOp(const A &ex) {
1073 ExtValue left = genval(ex.left());
1074 return createBinaryOp<OpTy>(left, genval(ex.right()));
1077 #undef GENBIN
1078 #define GENBIN(GenBinEvOp, GenBinTyCat, GenBinFirOp) \
1079 template <int KIND> \
1080 ExtValue genval(const Fortran::evaluate::GenBinEvOp<Fortran::evaluate::Type< \
1081 Fortran::common::TypeCategory::GenBinTyCat, KIND>> &x) { \
1082 return createBinaryOp<GenBinFirOp>(x); \
1085 GENBIN(Add, Integer, mlir::arith::AddIOp)
1086 GENBIN(Add, Real, mlir::arith::AddFOp)
1087 GENBIN(Add, Complex, fir::AddcOp)
1088 GENBIN(Subtract, Integer, mlir::arith::SubIOp)
1089 GENBIN(Subtract, Real, mlir::arith::SubFOp)
1090 GENBIN(Subtract, Complex, fir::SubcOp)
1091 GENBIN(Multiply, Integer, mlir::arith::MulIOp)
1092 GENBIN(Multiply, Real, mlir::arith::MulFOp)
1093 GENBIN(Multiply, Complex, fir::MulcOp)
1094 GENBIN(Divide, Integer, mlir::arith::DivSIOp)
1095 GENBIN(Divide, Real, mlir::arith::DivFOp)
1097 template <int KIND>
1098 ExtValue genval(const Fortran::evaluate::Divide<Fortran::evaluate::Type<
1099 Fortran::common::TypeCategory::Complex, KIND>> &op) {
1100 mlir::Type ty =
1101 converter.genType(Fortran::common::TypeCategory::Complex, KIND);
1102 mlir::Value lhs = genunbox(op.left());
1103 mlir::Value rhs = genunbox(op.right());
1104 return fir::genDivC(builder, getLoc(), ty, lhs, rhs);
1107 template <Fortran::common::TypeCategory TC, int KIND>
1108 ExtValue genval(
1109 const Fortran::evaluate::Power<Fortran::evaluate::Type<TC, KIND>> &op) {
1110 mlir::Type ty = converter.genType(TC, KIND);
1111 mlir::Value lhs = genunbox(op.left());
1112 mlir::Value rhs = genunbox(op.right());
1113 return fir::genPow(builder, getLoc(), ty, lhs, rhs);
1116 template <Fortran::common::TypeCategory TC, int KIND>
1117 ExtValue genval(
1118 const Fortran::evaluate::RealToIntPower<Fortran::evaluate::Type<TC, KIND>>
1119 &op) {
1120 mlir::Type ty = converter.genType(TC, KIND);
1121 mlir::Value lhs = genunbox(op.left());
1122 mlir::Value rhs = genunbox(op.right());
1123 return fir::genPow(builder, getLoc(), ty, lhs, rhs);
1126 template <int KIND>
1127 ExtValue genval(const Fortran::evaluate::ComplexConstructor<KIND> &op) {
1128 mlir::Value realPartValue = genunbox(op.left());
1129 return fir::factory::Complex{builder, getLoc()}.createComplex(
1130 KIND, realPartValue, genunbox(op.right()));
1133 template <int KIND>
1134 ExtValue genval(const Fortran::evaluate::Concat<KIND> &op) {
1135 ExtValue lhs = genval(op.left());
1136 ExtValue rhs = genval(op.right());
1137 const fir::CharBoxValue *lhsChar = lhs.getCharBox();
1138 const fir::CharBoxValue *rhsChar = rhs.getCharBox();
1139 if (lhsChar && rhsChar)
1140 return fir::factory::CharacterExprHelper{builder, getLoc()}
1141 .createConcatenate(*lhsChar, *rhsChar);
1142 TODO(getLoc(), "character array concatenate");
1145 /// MIN and MAX operations
1146 template <Fortran::common::TypeCategory TC, int KIND>
1147 ExtValue
1148 genval(const Fortran::evaluate::Extremum<Fortran::evaluate::Type<TC, KIND>>
1149 &op) {
1150 mlir::Value lhs = genunbox(op.left());
1151 mlir::Value rhs = genunbox(op.right());
1152 switch (op.ordering) {
1153 case Fortran::evaluate::Ordering::Greater:
1154 return fir::genMax(builder, getLoc(),
1155 llvm::ArrayRef<mlir::Value>{lhs, rhs});
1156 case Fortran::evaluate::Ordering::Less:
1157 return fir::genMin(builder, getLoc(),
1158 llvm::ArrayRef<mlir::Value>{lhs, rhs});
1159 case Fortran::evaluate::Ordering::Equal:
1160 llvm_unreachable("Equal is not a valid ordering in this context");
1162 llvm_unreachable("unknown ordering");
1165 // Change the dynamic length information without actually changing the
1166 // underlying character storage.
1167 fir::ExtendedValue
1168 replaceScalarCharacterLength(const fir::ExtendedValue &scalarChar,
1169 mlir::Value newLenValue) {
1170 mlir::Location loc = getLoc();
1171 const fir::CharBoxValue *charBox = scalarChar.getCharBox();
1172 if (!charBox)
1173 fir::emitFatalError(loc, "expected scalar character");
1174 mlir::Value charAddr = charBox->getAddr();
1175 auto charType = mlir::cast<fir::CharacterType>(
1176 fir::unwrapPassByRefType(charAddr.getType()));
1177 if (charType.hasConstantLen()) {
1178 // Erase previous constant length from the base type.
1179 fir::CharacterType::LenType newLen = fir::CharacterType::unknownLen();
1180 mlir::Type newCharTy = fir::CharacterType::get(
1181 builder.getContext(), charType.getFKind(), newLen);
1182 mlir::Type newType = fir::ReferenceType::get(newCharTy);
1183 charAddr = builder.createConvert(loc, newType, charAddr);
1184 return fir::CharBoxValue{charAddr, newLenValue};
1186 return fir::CharBoxValue{charAddr, newLenValue};
1189 template <int KIND>
1190 ExtValue genval(const Fortran::evaluate::SetLength<KIND> &x) {
1191 mlir::Value newLenValue = genunbox(x.right());
1192 fir::ExtendedValue lhs = gen(x.left());
1193 fir::factory::CharacterExprHelper charHelper(builder, getLoc());
1194 fir::CharBoxValue temp = charHelper.createCharacterTemp(
1195 charHelper.getCharacterType(fir::getBase(lhs).getType()), newLenValue);
1196 charHelper.createAssign(temp, lhs);
1197 return fir::ExtendedValue{temp};
1200 template <int KIND>
1201 ExtValue genval(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
1202 Fortran::common::TypeCategory::Integer, KIND>> &op) {
1203 return createCompareOp<mlir::arith::CmpIOp>(op,
1204 translateRelational(op.opr));
1206 template <int KIND>
1207 ExtValue genval(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
1208 Fortran::common::TypeCategory::Real, KIND>> &op) {
1209 return createFltCmpOp<mlir::arith::CmpFOp>(
1210 op, translateFloatRelational(op.opr));
1212 template <int KIND>
1213 ExtValue genval(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
1214 Fortran::common::TypeCategory::Complex, KIND>> &op) {
1215 return createFltCmpOp<fir::CmpcOp>(op, translateFloatRelational(op.opr));
1217 template <int KIND>
1218 ExtValue genval(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
1219 Fortran::common::TypeCategory::Character, KIND>> &op) {
1220 return createCharCompare(op, translateRelational(op.opr));
1223 ExtValue
1224 genval(const Fortran::evaluate::Relational<Fortran::evaluate::SomeType> &op) {
1225 return Fortran::common::visit([&](const auto &x) { return genval(x); },
1226 op.u);
1229 template <Fortran::common::TypeCategory TC1, int KIND,
1230 Fortran::common::TypeCategory TC2>
1231 ExtValue
1232 genval(const Fortran::evaluate::Convert<Fortran::evaluate::Type<TC1, KIND>,
1233 TC2> &convert) {
1234 mlir::Type ty = converter.genType(TC1, KIND);
1235 auto fromExpr = genval(convert.left());
1236 auto loc = getLoc();
1237 return fromExpr.match(
1238 [&](const fir::CharBoxValue &boxchar) -> ExtValue {
1239 if constexpr (TC1 == Fortran::common::TypeCategory::Character &&
1240 TC2 == TC1) {
1241 return fir::factory::convertCharacterKind(builder, loc, boxchar,
1242 KIND);
1243 } else {
1244 fir::emitFatalError(
1245 loc, "unsupported evaluate::Convert between CHARACTER type "
1246 "category and non-CHARACTER category");
1249 [&](const fir::UnboxedValue &value) -> ExtValue {
1250 return builder.convertWithSemantics(loc, ty, value);
1252 [&](auto &) -> ExtValue {
1253 fir::emitFatalError(loc, "unsupported evaluate::Convert");
1257 template <typename A>
1258 ExtValue genval(const Fortran::evaluate::Parentheses<A> &op) {
1259 ExtValue input = genval(op.left());
1260 mlir::Value base = fir::getBase(input);
1261 mlir::Value newBase =
1262 builder.create<fir::NoReassocOp>(getLoc(), base.getType(), base);
1263 return fir::substBase(input, newBase);
1266 template <int KIND>
1267 ExtValue genval(const Fortran::evaluate::Not<KIND> &op) {
1268 mlir::Value logical = genunbox(op.left());
1269 mlir::Value one = genBoolConstant(true);
1270 mlir::Value val =
1271 builder.createConvert(getLoc(), builder.getI1Type(), logical);
1272 return builder.create<mlir::arith::XOrIOp>(getLoc(), val, one);
1275 template <int KIND>
1276 ExtValue genval(const Fortran::evaluate::LogicalOperation<KIND> &op) {
1277 mlir::IntegerType i1Type = builder.getI1Type();
1278 mlir::Value slhs = genunbox(op.left());
1279 mlir::Value srhs = genunbox(op.right());
1280 mlir::Value lhs = builder.createConvert(getLoc(), i1Type, slhs);
1281 mlir::Value rhs = builder.createConvert(getLoc(), i1Type, srhs);
1282 switch (op.logicalOperator) {
1283 case Fortran::evaluate::LogicalOperator::And:
1284 return createBinaryOp<mlir::arith::AndIOp>(lhs, rhs);
1285 case Fortran::evaluate::LogicalOperator::Or:
1286 return createBinaryOp<mlir::arith::OrIOp>(lhs, rhs);
1287 case Fortran::evaluate::LogicalOperator::Eqv:
1288 return createCompareOp<mlir::arith::CmpIOp>(
1289 mlir::arith::CmpIPredicate::eq, lhs, rhs);
1290 case Fortran::evaluate::LogicalOperator::Neqv:
1291 return createCompareOp<mlir::arith::CmpIOp>(
1292 mlir::arith::CmpIPredicate::ne, lhs, rhs);
1293 case Fortran::evaluate::LogicalOperator::Not:
1294 // lib/evaluate expression for .NOT. is Fortran::evaluate::Not<KIND>.
1295 llvm_unreachable(".NOT. is not a binary operator");
1297 llvm_unreachable("unhandled logical operation");
1300 template <Fortran::common::TypeCategory TC, int KIND>
1301 ExtValue
1302 genval(const Fortran::evaluate::Constant<Fortran::evaluate::Type<TC, KIND>>
1303 &con) {
1304 return Fortran::lower::convertConstant(
1305 converter, getLoc(), con,
1306 /*outlineBigConstantsInReadOnlyMemory=*/!inInitializer);
1309 fir::ExtendedValue genval(
1310 const Fortran::evaluate::Constant<Fortran::evaluate::SomeDerived> &con) {
1311 if (auto ctor = con.GetScalarValue())
1312 return genval(*ctor);
1313 return Fortran::lower::convertConstant(
1314 converter, getLoc(), con,
1315 /*outlineBigConstantsInReadOnlyMemory=*/false);
1318 template <typename A>
1319 ExtValue genval(const Fortran::evaluate::ArrayConstructor<A> &) {
1320 fir::emitFatalError(getLoc(), "array constructor: should not reach here");
1323 ExtValue gen(const Fortran::evaluate::ComplexPart &x) {
1324 mlir::Location loc = getLoc();
1325 auto idxTy = builder.getI32Type();
1326 ExtValue exv = gen(x.complex());
1327 mlir::Value base = fir::getBase(exv);
1328 fir::factory::Complex helper{builder, loc};
1329 mlir::Type eleTy =
1330 helper.getComplexPartType(fir::dyn_cast_ptrEleTy(base.getType()));
1331 mlir::Value offset = builder.createIntegerConstant(
1332 loc, idxTy,
1333 x.part() == Fortran::evaluate::ComplexPart::Part::RE ? 0 : 1);
1334 mlir::Value result = builder.create<fir::CoordinateOp>(
1335 loc, builder.getRefType(eleTy), base, mlir::ValueRange{offset});
1336 return {result};
1338 ExtValue genval(const Fortran::evaluate::ComplexPart &x) {
1339 return genLoad(gen(x));
1342 /// Reference to a substring.
1343 ExtValue gen(const Fortran::evaluate::Substring &s) {
1344 // Get base string
1345 auto baseString = Fortran::common::visit(
1346 Fortran::common::visitors{
1347 [&](const Fortran::evaluate::DataRef &x) { return gen(x); },
1348 [&](const Fortran::evaluate::StaticDataObject::Pointer &p)
1349 -> ExtValue {
1350 if (std::optional<std::string> str = p->AsString())
1351 return fir::factory::createStringLiteral(builder, getLoc(),
1352 *str);
1353 // TODO: convert StaticDataObject to Constant<T> and use normal
1354 // constant path. Beware that StaticDataObject data() takes into
1355 // account build machine endianness.
1356 TODO(getLoc(),
1357 "StaticDataObject::Pointer substring with kind > 1");
1360 s.parent());
1361 llvm::SmallVector<mlir::Value> bounds;
1362 mlir::Value lower = genunbox(s.lower());
1363 bounds.push_back(lower);
1364 if (Fortran::evaluate::MaybeExtentExpr upperBound = s.upper()) {
1365 mlir::Value upper = genunbox(*upperBound);
1366 bounds.push_back(upper);
1368 fir::factory::CharacterExprHelper charHelper{builder, getLoc()};
1369 return baseString.match(
1370 [&](const fir::CharBoxValue &x) -> ExtValue {
1371 return charHelper.createSubstring(x, bounds);
1373 [&](const fir::CharArrayBoxValue &) -> ExtValue {
1374 fir::emitFatalError(
1375 getLoc(),
1376 "array substring should be handled in array expression");
1378 [&](const auto &) -> ExtValue {
1379 fir::emitFatalError(getLoc(), "substring base is not a CharBox");
1383 /// The value of a substring.
1384 ExtValue genval(const Fortran::evaluate::Substring &ss) {
1385 // FIXME: why is the value of a substring being lowered the same as the
1386 // address of a substring?
1387 return gen(ss);
1390 ExtValue genval(const Fortran::evaluate::Subscript &subs) {
1391 if (auto *s = std::get_if<Fortran::evaluate::IndirectSubscriptIntegerExpr>(
1392 &subs.u)) {
1393 if (s->value().Rank() > 0)
1394 fir::emitFatalError(getLoc(), "vector subscript is not scalar");
1395 return {genval(s->value())};
1397 fir::emitFatalError(getLoc(), "subscript triple notation is not scalar");
1399 ExtValue genSubscript(const Fortran::evaluate::Subscript &subs) {
1400 return genval(subs);
1403 ExtValue gen(const Fortran::evaluate::DataRef &dref) {
1404 return Fortran::common::visit([&](const auto &x) { return gen(x); },
1405 dref.u);
1407 ExtValue genval(const Fortran::evaluate::DataRef &dref) {
1408 return Fortran::common::visit([&](const auto &x) { return genval(x); },
1409 dref.u);
1412 // Helper function to turn the Component structure into a list of nested
1413 // components, ordered from largest/leftmost to smallest/rightmost:
1414 // - where only the smallest/rightmost item may be allocatable or a pointer
1415 // (nested allocatable/pointer components require nested coordinate_of ops)
1416 // - that does not contain any parent components
1417 // (the front end places parent components directly in the object)
1418 // Return the object used as the base coordinate for the component chain.
1419 static Fortran::evaluate::DataRef const *
1420 reverseComponents(const Fortran::evaluate::Component &cmpt,
1421 std::list<const Fortran::evaluate::Component *> &list) {
1422 if (!getLastSym(cmpt).test(Fortran::semantics::Symbol::Flag::ParentComp))
1423 list.push_front(&cmpt);
1424 return Fortran::common::visit(
1425 Fortran::common::visitors{
1426 [&](const Fortran::evaluate::Component &x) {
1427 if (Fortran::semantics::IsAllocatableOrPointer(getLastSym(x)))
1428 return &cmpt.base();
1429 return reverseComponents(x, list);
1431 [&](auto &) { return &cmpt.base(); },
1433 cmpt.base().u);
1436 // Return the coordinate of the component reference
1437 ExtValue genComponent(const Fortran::evaluate::Component &cmpt) {
1438 std::list<const Fortran::evaluate::Component *> list;
1439 const Fortran::evaluate::DataRef *base = reverseComponents(cmpt, list);
1440 llvm::SmallVector<mlir::Value> coorArgs;
1441 ExtValue obj = gen(*base);
1442 mlir::Type ty = fir::dyn_cast_ptrOrBoxEleTy(fir::getBase(obj).getType());
1443 mlir::Location loc = getLoc();
1444 auto fldTy = fir::FieldType::get(&converter.getMLIRContext());
1445 // FIXME: need to thread the LEN type parameters here.
1446 for (const Fortran::evaluate::Component *field : list) {
1447 auto recTy = mlir::cast<fir::RecordType>(ty);
1448 const Fortran::semantics::Symbol &sym = getLastSym(*field);
1449 std::string name = converter.getRecordTypeFieldName(sym);
1450 coorArgs.push_back(builder.create<fir::FieldIndexOp>(
1451 loc, fldTy, name, recTy, fir::getTypeParams(obj)));
1452 ty = recTy.getType(name);
1454 // If parent component is referred then it has no coordinate argument.
1455 if (coorArgs.size() == 0)
1456 return obj;
1457 ty = builder.getRefType(ty);
1458 return fir::factory::componentToExtendedValue(
1459 builder, loc,
1460 builder.create<fir::CoordinateOp>(loc, ty, fir::getBase(obj),
1461 coorArgs));
1464 ExtValue gen(const Fortran::evaluate::Component &cmpt) {
1465 // Components may be pointer or allocatable. In the gen() path, the mutable
1466 // aspect is lost to simplify handling on the client side. To retain the
1467 // mutable aspect, genMutableBoxValue should be used.
1468 return genComponent(cmpt).match(
1469 [&](const fir::MutableBoxValue &mutableBox) {
1470 return fir::factory::genMutableBoxRead(builder, getLoc(), mutableBox);
1472 [](auto &box) -> ExtValue { return box; });
1475 ExtValue genval(const Fortran::evaluate::Component &cmpt) {
1476 return genLoad(gen(cmpt));
1479 // Determine the result type after removing `dims` dimensions from the array
1480 // type `arrTy`
1481 mlir::Type genSubType(mlir::Type arrTy, unsigned dims) {
1482 mlir::Type unwrapTy = fir::dyn_cast_ptrOrBoxEleTy(arrTy);
1483 assert(unwrapTy && "must be a pointer or box type");
1484 auto seqTy = mlir::cast<fir::SequenceType>(unwrapTy);
1485 llvm::ArrayRef<int64_t> shape = seqTy.getShape();
1486 assert(shape.size() > 0 && "removing columns for sequence sans shape");
1487 assert(dims <= shape.size() && "removing more columns than exist");
1488 fir::SequenceType::Shape newBnds;
1489 // follow Fortran semantics and remove columns (from right)
1490 std::size_t e = shape.size() - dims;
1491 for (decltype(e) i = 0; i < e; ++i)
1492 newBnds.push_back(shape[i]);
1493 if (!newBnds.empty())
1494 return fir::SequenceType::get(newBnds, seqTy.getEleTy());
1495 return seqTy.getEleTy();
1498 // Generate the code for a Bound value.
1499 ExtValue genval(const Fortran::semantics::Bound &bound) {
1500 if (bound.isExplicit()) {
1501 Fortran::semantics::MaybeSubscriptIntExpr sub = bound.GetExplicit();
1502 if (sub.has_value())
1503 return genval(*sub);
1504 return genIntegerConstant<8>(builder.getContext(), 1);
1506 TODO(getLoc(), "non explicit semantics::Bound implementation");
1509 static bool isSlice(const Fortran::evaluate::ArrayRef &aref) {
1510 for (const Fortran::evaluate::Subscript &sub : aref.subscript())
1511 if (std::holds_alternative<Fortran::evaluate::Triplet>(sub.u))
1512 return true;
1513 return false;
1516 /// Lower an ArrayRef to a fir.coordinate_of given its lowered base.
1517 ExtValue genCoordinateOp(const ExtValue &array,
1518 const Fortran::evaluate::ArrayRef &aref) {
1519 mlir::Location loc = getLoc();
1520 // References to array of rank > 1 with non constant shape that are not
1521 // fir.box must be collapsed into an offset computation in lowering already.
1522 // The same is needed with dynamic length character arrays of all ranks.
1523 mlir::Type baseType =
1524 fir::dyn_cast_ptrOrBoxEleTy(fir::getBase(array).getType());
1525 if ((array.rank() > 1 && fir::hasDynamicSize(baseType)) ||
1526 fir::characterWithDynamicLen(fir::unwrapSequenceType(baseType)))
1527 if (!array.getBoxOf<fir::BoxValue>())
1528 return genOffsetAndCoordinateOp(array, aref);
1529 // Generate a fir.coordinate_of with zero based array indexes.
1530 llvm::SmallVector<mlir::Value> args;
1531 for (const auto &subsc : llvm::enumerate(aref.subscript())) {
1532 ExtValue subVal = genSubscript(subsc.value());
1533 assert(fir::isUnboxedValue(subVal) && "subscript must be simple scalar");
1534 mlir::Value val = fir::getBase(subVal);
1535 mlir::Type ty = val.getType();
1536 mlir::Value lb = getLBound(array, subsc.index(), ty);
1537 args.push_back(builder.create<mlir::arith::SubIOp>(loc, ty, val, lb));
1539 mlir::Value base = fir::getBase(array);
1541 auto baseSym = getFirstSym(aref);
1542 if (baseSym.test(Fortran::semantics::Symbol::Flag::CrayPointee)) {
1543 // get the corresponding Cray pointer
1544 Fortran::semantics::SymbolRef ptrSym{
1545 Fortran::semantics::GetCrayPointer(baseSym)};
1546 fir::ExtendedValue ptr = gen(ptrSym);
1547 mlir::Value ptrVal = fir::getBase(ptr);
1548 mlir::Type ptrTy = ptrVal.getType();
1550 mlir::Value cnvrt = Fortran::lower::addCrayPointerInst(
1551 loc, builder, ptrVal, ptrTy, base.getType());
1552 base = builder.create<fir::LoadOp>(loc, cnvrt);
1555 mlir::Type eleTy = fir::dyn_cast_ptrOrBoxEleTy(base.getType());
1556 if (auto classTy = mlir::dyn_cast<fir::ClassType>(eleTy))
1557 eleTy = classTy.getEleTy();
1558 auto seqTy = mlir::cast<fir::SequenceType>(eleTy);
1559 assert(args.size() == seqTy.getDimension());
1560 mlir::Type ty = builder.getRefType(seqTy.getEleTy());
1561 auto addr = builder.create<fir::CoordinateOp>(loc, ty, base, args);
1562 return fir::factory::arrayElementToExtendedValue(builder, loc, array, addr);
1565 /// Lower an ArrayRef to a fir.coordinate_of using an element offset instead
1566 /// of array indexes.
1567 /// This generates offset computation from the indexes and length parameters,
1568 /// and use the offset to access the element with a fir.coordinate_of. This
1569 /// must only be used if it is not possible to generate a normal
1570 /// fir.coordinate_of using array indexes (i.e. when the shape information is
1571 /// unavailable in the IR).
1572 ExtValue genOffsetAndCoordinateOp(const ExtValue &array,
1573 const Fortran::evaluate::ArrayRef &aref) {
1574 mlir::Location loc = getLoc();
1575 mlir::Value addr = fir::getBase(array);
1576 mlir::Type arrTy = fir::dyn_cast_ptrEleTy(addr.getType());
1577 auto eleTy = mlir::cast<fir::SequenceType>(arrTy).getEleTy();
1578 mlir::Type seqTy = builder.getRefType(builder.getVarLenSeqTy(eleTy));
1579 mlir::Type refTy = builder.getRefType(eleTy);
1580 mlir::Value base = builder.createConvert(loc, seqTy, addr);
1581 mlir::IndexType idxTy = builder.getIndexType();
1582 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
1583 mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0);
1584 auto getLB = [&](const auto &arr, unsigned dim) -> mlir::Value {
1585 return arr.getLBounds().empty() ? one : arr.getLBounds()[dim];
1587 auto genFullDim = [&](const auto &arr, mlir::Value delta) -> mlir::Value {
1588 mlir::Value total = zero;
1589 assert(arr.getExtents().size() == aref.subscript().size());
1590 delta = builder.createConvert(loc, idxTy, delta);
1591 unsigned dim = 0;
1592 for (auto [ext, sub] : llvm::zip(arr.getExtents(), aref.subscript())) {
1593 ExtValue subVal = genSubscript(sub);
1594 assert(fir::isUnboxedValue(subVal));
1595 mlir::Value val =
1596 builder.createConvert(loc, idxTy, fir::getBase(subVal));
1597 mlir::Value lb = builder.createConvert(loc, idxTy, getLB(arr, dim));
1598 mlir::Value diff = builder.create<mlir::arith::SubIOp>(loc, val, lb);
1599 mlir::Value prod =
1600 builder.create<mlir::arith::MulIOp>(loc, delta, diff);
1601 total = builder.create<mlir::arith::AddIOp>(loc, prod, total);
1602 if (ext)
1603 delta = builder.create<mlir::arith::MulIOp>(loc, delta, ext);
1604 ++dim;
1606 mlir::Type origRefTy = refTy;
1607 if (fir::factory::CharacterExprHelper::isCharacterScalar(refTy)) {
1608 fir::CharacterType chTy =
1609 fir::factory::CharacterExprHelper::getCharacterType(refTy);
1610 if (fir::characterWithDynamicLen(chTy)) {
1611 mlir::MLIRContext *ctx = builder.getContext();
1612 fir::KindTy kind =
1613 fir::factory::CharacterExprHelper::getCharacterKind(chTy);
1614 fir::CharacterType singleTy =
1615 fir::CharacterType::getSingleton(ctx, kind);
1616 refTy = builder.getRefType(singleTy);
1617 mlir::Type seqRefTy =
1618 builder.getRefType(builder.getVarLenSeqTy(singleTy));
1619 base = builder.createConvert(loc, seqRefTy, base);
1622 auto coor = builder.create<fir::CoordinateOp>(
1623 loc, refTy, base, llvm::ArrayRef<mlir::Value>{total});
1624 // Convert to expected, original type after address arithmetic.
1625 return builder.createConvert(loc, origRefTy, coor);
1627 return array.match(
1628 [&](const fir::ArrayBoxValue &arr) -> ExtValue {
1629 // FIXME: this check can be removed when slicing is implemented
1630 if (isSlice(aref))
1631 fir::emitFatalError(
1632 getLoc(),
1633 "slice should be handled in array expression context");
1634 return genFullDim(arr, one);
1636 [&](const fir::CharArrayBoxValue &arr) -> ExtValue {
1637 mlir::Value delta = arr.getLen();
1638 // If the length is known in the type, fir.coordinate_of will
1639 // already take the length into account.
1640 if (fir::factory::CharacterExprHelper::hasConstantLengthInType(arr))
1641 delta = one;
1642 return fir::CharBoxValue(genFullDim(arr, delta), arr.getLen());
1644 [&](const fir::BoxValue &arr) -> ExtValue {
1645 // CoordinateOp for BoxValue is not generated here. The dimensions
1646 // must be kept in the fir.coordinate_op so that potential fir.box
1647 // strides can be applied by codegen.
1648 fir::emitFatalError(
1649 loc, "internal: BoxValue in dim-collapsed fir.coordinate_of");
1651 [&](const auto &) -> ExtValue {
1652 fir::emitFatalError(loc, "internal: array processing failed");
1656 /// Lower an ArrayRef to a fir.array_coor.
1657 ExtValue genArrayCoorOp(const ExtValue &exv,
1658 const Fortran::evaluate::ArrayRef &aref) {
1659 mlir::Location loc = getLoc();
1660 mlir::Value addr = fir::getBase(exv);
1661 mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(addr.getType());
1662 mlir::Type eleTy = mlir::cast<fir::SequenceType>(arrTy).getEleTy();
1663 mlir::Type refTy = builder.getRefType(eleTy);
1664 mlir::IndexType idxTy = builder.getIndexType();
1665 llvm::SmallVector<mlir::Value> arrayCoorArgs;
1666 // The ArrayRef is expected to be scalar here, arrays are handled in array
1667 // expression lowering. So no vector subscript or triplet is expected here.
1668 for (const auto &sub : aref.subscript()) {
1669 ExtValue subVal = genSubscript(sub);
1670 assert(fir::isUnboxedValue(subVal));
1671 arrayCoorArgs.push_back(
1672 builder.createConvert(loc, idxTy, fir::getBase(subVal)));
1674 mlir::Value shape = builder.createShape(loc, exv);
1675 mlir::Value elementAddr = builder.create<fir::ArrayCoorOp>(
1676 loc, refTy, addr, shape, /*slice=*/mlir::Value{}, arrayCoorArgs,
1677 fir::getTypeParams(exv));
1678 return fir::factory::arrayElementToExtendedValue(builder, loc, exv,
1679 elementAddr);
1682 /// Return the coordinate of the array reference.
1683 ExtValue gen(const Fortran::evaluate::ArrayRef &aref) {
1684 ExtValue base = aref.base().IsSymbol() ? gen(getFirstSym(aref.base()))
1685 : gen(aref.base().GetComponent());
1686 // Check for command-line override to use array_coor op.
1687 if (generateArrayCoordinate)
1688 return genArrayCoorOp(base, aref);
1689 // Otherwise, use coordinate_of op.
1690 return genCoordinateOp(base, aref);
1693 /// Return lower bounds of \p box in dimension \p dim. The returned value
1694 /// has type \ty.
1695 mlir::Value getLBound(const ExtValue &box, unsigned dim, mlir::Type ty) {
1696 assert(box.rank() > 0 && "must be an array");
1697 mlir::Location loc = getLoc();
1698 mlir::Value one = builder.createIntegerConstant(loc, ty, 1);
1699 mlir::Value lb = fir::factory::readLowerBound(builder, loc, box, dim, one);
1700 return builder.createConvert(loc, ty, lb);
1703 ExtValue genval(const Fortran::evaluate::ArrayRef &aref) {
1704 return genLoad(gen(aref));
1707 ExtValue gen(const Fortran::evaluate::CoarrayRef &coref) {
1708 return Fortran::lower::CoarrayExprHelper{converter, getLoc(), symMap}
1709 .genAddr(coref);
1712 ExtValue genval(const Fortran::evaluate::CoarrayRef &coref) {
1713 return Fortran::lower::CoarrayExprHelper{converter, getLoc(), symMap}
1714 .genValue(coref);
1717 template <typename A>
1718 ExtValue gen(const Fortran::evaluate::Designator<A> &des) {
1719 return Fortran::common::visit([&](const auto &x) { return gen(x); }, des.u);
1721 template <typename A>
1722 ExtValue genval(const Fortran::evaluate::Designator<A> &des) {
1723 return Fortran::common::visit([&](const auto &x) { return genval(x); },
1724 des.u);
1727 mlir::Type genType(const Fortran::evaluate::DynamicType &dt) {
1728 if (dt.category() != Fortran::common::TypeCategory::Derived)
1729 return converter.genType(dt.category(), dt.kind());
1730 if (dt.IsUnlimitedPolymorphic())
1731 return mlir::NoneType::get(&converter.getMLIRContext());
1732 return converter.genType(dt.GetDerivedTypeSpec());
1735 /// Lower a function reference
1736 template <typename A>
1737 ExtValue genFunctionRef(const Fortran::evaluate::FunctionRef<A> &funcRef) {
1738 if (!funcRef.GetType().has_value())
1739 fir::emitFatalError(getLoc(), "a function must have a type");
1740 mlir::Type resTy = genType(*funcRef.GetType());
1741 return genProcedureRef(funcRef, {resTy});
1744 /// Lower function call `funcRef` and return a reference to the resultant
1745 /// value. This is required for lowering expressions such as `f1(f2(v))`.
1746 template <typename A>
1747 ExtValue gen(const Fortran::evaluate::FunctionRef<A> &funcRef) {
1748 ExtValue retVal = genFunctionRef(funcRef);
1749 mlir::Type resultType = converter.genType(toEvExpr(funcRef));
1750 return placeScalarValueInMemory(builder, getLoc(), retVal, resultType);
1753 /// Helper to lower intrinsic arguments for inquiry intrinsic.
1754 ExtValue
1755 lowerIntrinsicArgumentAsInquired(const Fortran::lower::SomeExpr &expr) {
1756 if (Fortran::evaluate::IsAllocatableOrPointerObject(expr))
1757 return genMutableBoxValue(expr);
1758 /// Do not create temps for array sections whose properties only need to be
1759 /// inquired: create a descriptor that will be inquired.
1760 if (Fortran::evaluate::IsVariable(expr) && isArray(expr) &&
1761 !Fortran::evaluate::UnwrapWholeSymbolOrComponentDataRef(expr))
1762 return lowerIntrinsicArgumentAsBox(expr);
1763 return gen(expr);
1766 /// Helper to lower intrinsic arguments to a fir::BoxValue.
1767 /// It preserves all the non default lower bounds/non deferred length
1768 /// parameter information.
1769 ExtValue lowerIntrinsicArgumentAsBox(const Fortran::lower::SomeExpr &expr) {
1770 mlir::Location loc = getLoc();
1771 ExtValue exv = genBoxArg(expr);
1772 auto exvTy = fir::getBase(exv).getType();
1773 if (mlir::isa<mlir::FunctionType>(exvTy)) {
1774 auto boxProcTy =
1775 builder.getBoxProcType(mlir::cast<mlir::FunctionType>(exvTy));
1776 return builder.create<fir::EmboxProcOp>(loc, boxProcTy,
1777 fir::getBase(exv));
1779 mlir::Value box = builder.createBox(loc, exv, exv.isPolymorphic());
1780 if (Fortran::lower::isParentComponent(expr)) {
1781 fir::ExtendedValue newExv =
1782 Fortran::lower::updateBoxForParentComponent(converter, box, expr);
1783 box = fir::getBase(newExv);
1785 return fir::BoxValue(
1786 box, fir::factory::getNonDefaultLowerBounds(builder, loc, exv),
1787 fir::factory::getNonDeferredLenParams(exv));
1790 /// Generate a call to a Fortran intrinsic or intrinsic module procedure.
1791 ExtValue genIntrinsicRef(
1792 const Fortran::evaluate::ProcedureRef &procRef,
1793 std::optional<mlir::Type> resultType,
1794 std::optional<const Fortran::evaluate::SpecificIntrinsic> intrinsic =
1795 std::nullopt) {
1796 llvm::SmallVector<ExtValue> operands;
1798 std::string name =
1799 intrinsic ? intrinsic->name
1800 : procRef.proc().GetSymbol()->GetUltimate().name().ToString();
1801 mlir::Location loc = getLoc();
1802 if (intrinsic && Fortran::lower::intrinsicRequiresCustomOptionalHandling(
1803 procRef, *intrinsic, converter)) {
1804 using ExvAndPresence = std::pair<ExtValue, std::optional<mlir::Value>>;
1805 llvm::SmallVector<ExvAndPresence, 4> operands;
1806 auto prepareOptionalArg = [&](const Fortran::lower::SomeExpr &expr) {
1807 ExtValue optionalArg = lowerIntrinsicArgumentAsInquired(expr);
1808 mlir::Value isPresent =
1809 genActualIsPresentTest(builder, loc, optionalArg);
1810 operands.emplace_back(optionalArg, isPresent);
1812 auto prepareOtherArg = [&](const Fortran::lower::SomeExpr &expr,
1813 fir::LowerIntrinsicArgAs lowerAs) {
1814 switch (lowerAs) {
1815 case fir::LowerIntrinsicArgAs::Value:
1816 operands.emplace_back(genval(expr), std::nullopt);
1817 return;
1818 case fir::LowerIntrinsicArgAs::Addr:
1819 operands.emplace_back(gen(expr), std::nullopt);
1820 return;
1821 case fir::LowerIntrinsicArgAs::Box:
1822 operands.emplace_back(lowerIntrinsicArgumentAsBox(expr),
1823 std::nullopt);
1824 return;
1825 case fir::LowerIntrinsicArgAs::Inquired:
1826 operands.emplace_back(lowerIntrinsicArgumentAsInquired(expr),
1827 std::nullopt);
1828 return;
1831 Fortran::lower::prepareCustomIntrinsicArgument(
1832 procRef, *intrinsic, resultType, prepareOptionalArg, prepareOtherArg,
1833 converter);
1835 auto getArgument = [&](std::size_t i, bool loadArg) -> ExtValue {
1836 if (loadArg && fir::conformsWithPassByRef(
1837 fir::getBase(operands[i].first).getType()))
1838 return genLoad(operands[i].first);
1839 return operands[i].first;
1841 auto isPresent = [&](std::size_t i) -> std::optional<mlir::Value> {
1842 return operands[i].second;
1844 return Fortran::lower::lowerCustomIntrinsic(
1845 builder, loc, name, resultType, isPresent, getArgument,
1846 operands.size(), stmtCtx);
1849 const fir::IntrinsicArgumentLoweringRules *argLowering =
1850 fir::getIntrinsicArgumentLowering(name);
1851 for (const auto &arg : llvm::enumerate(procRef.arguments())) {
1852 auto *expr =
1853 Fortran::evaluate::UnwrapExpr<Fortran::lower::SomeExpr>(arg.value());
1855 if (!expr && arg.value() && arg.value()->GetAssumedTypeDummy()) {
1856 // Assumed type optional.
1857 const Fortran::evaluate::Symbol *assumedTypeSym =
1858 arg.value()->GetAssumedTypeDummy();
1859 auto symBox = symMap.lookupSymbol(*assumedTypeSym);
1860 ExtValue exv =
1861 converter.getSymbolExtendedValue(*assumedTypeSym, &symMap);
1862 if (argLowering) {
1863 fir::ArgLoweringRule argRules =
1864 fir::lowerIntrinsicArgumentAs(*argLowering, arg.index());
1865 // Note: usages of TYPE(*) is limited by C710 but C_LOC and
1866 // IS_CONTIGUOUS may require an assumed size TYPE(*) to be passed to
1867 // the intrinsic library utility as a fir.box.
1868 if (argRules.lowerAs == fir::LowerIntrinsicArgAs::Box &&
1869 !mlir::isa<fir::BaseBoxType>(fir::getBase(exv).getType())) {
1870 operands.emplace_back(
1871 fir::factory::createBoxValue(builder, loc, exv));
1872 continue;
1875 operands.emplace_back(std::move(exv));
1876 continue;
1878 if (!expr) {
1879 // Absent optional.
1880 operands.emplace_back(fir::getAbsentIntrinsicArgument());
1881 continue;
1883 if (!argLowering) {
1884 // No argument lowering instruction, lower by value.
1885 operands.emplace_back(genval(*expr));
1886 continue;
1888 // Ad-hoc argument lowering handling.
1889 fir::ArgLoweringRule argRules =
1890 fir::lowerIntrinsicArgumentAs(*argLowering, arg.index());
1891 if (argRules.handleDynamicOptional &&
1892 Fortran::evaluate::MayBePassedAsAbsentOptional(*expr)) {
1893 ExtValue optional = lowerIntrinsicArgumentAsInquired(*expr);
1894 mlir::Value isPresent = genActualIsPresentTest(builder, loc, optional);
1895 switch (argRules.lowerAs) {
1896 case fir::LowerIntrinsicArgAs::Value:
1897 operands.emplace_back(
1898 genOptionalValue(builder, loc, optional, isPresent));
1899 continue;
1900 case fir::LowerIntrinsicArgAs::Addr:
1901 operands.emplace_back(
1902 genOptionalAddr(builder, loc, optional, isPresent));
1903 continue;
1904 case fir::LowerIntrinsicArgAs::Box:
1905 operands.emplace_back(
1906 genOptionalBox(builder, loc, optional, isPresent));
1907 continue;
1908 case fir::LowerIntrinsicArgAs::Inquired:
1909 operands.emplace_back(optional);
1910 continue;
1912 llvm_unreachable("bad switch");
1914 switch (argRules.lowerAs) {
1915 case fir::LowerIntrinsicArgAs::Value:
1916 operands.emplace_back(genval(*expr));
1917 continue;
1918 case fir::LowerIntrinsicArgAs::Addr:
1919 operands.emplace_back(gen(*expr));
1920 continue;
1921 case fir::LowerIntrinsicArgAs::Box:
1922 operands.emplace_back(lowerIntrinsicArgumentAsBox(*expr));
1923 continue;
1924 case fir::LowerIntrinsicArgAs::Inquired:
1925 operands.emplace_back(lowerIntrinsicArgumentAsInquired(*expr));
1926 continue;
1928 llvm_unreachable("bad switch");
1930 // Let the intrinsic library lower the intrinsic procedure call
1931 return Fortran::lower::genIntrinsicCall(builder, getLoc(), name, resultType,
1932 operands, stmtCtx, &converter);
1935 /// helper to detect statement functions
1936 static bool
1937 isStatementFunctionCall(const Fortran::evaluate::ProcedureRef &procRef) {
1938 if (const Fortran::semantics::Symbol *symbol = procRef.proc().GetSymbol())
1939 if (const auto *details =
1940 symbol->detailsIf<Fortran::semantics::SubprogramDetails>())
1941 return details->stmtFunction().has_value();
1942 return false;
1945 /// Generate Statement function calls
1946 ExtValue genStmtFunctionRef(const Fortran::evaluate::ProcedureRef &procRef) {
1947 const Fortran::semantics::Symbol *symbol = procRef.proc().GetSymbol();
1948 assert(symbol && "expected symbol in ProcedureRef of statement functions");
1949 const auto &details = symbol->get<Fortran::semantics::SubprogramDetails>();
1951 // Statement functions have their own scope, we just need to associate
1952 // the dummy symbols to argument expressions. They are no
1953 // optional/alternate return arguments. Statement functions cannot be
1954 // recursive (directly or indirectly) so it is safe to add dummy symbols to
1955 // the local map here.
1956 symMap.pushScope();
1957 for (auto [arg, bind] :
1958 llvm::zip(details.dummyArgs(), procRef.arguments())) {
1959 assert(arg && "alternate return in statement function");
1960 assert(bind && "optional argument in statement function");
1961 const auto *expr = bind->UnwrapExpr();
1962 // TODO: assumed type in statement function, that surprisingly seems
1963 // allowed, probably because nobody thought of restricting this usage.
1964 // gfortran/ifort compiles this.
1965 assert(expr && "assumed type used as statement function argument");
1966 // As per Fortran 2018 C1580, statement function arguments can only be
1967 // scalars, so just pass the box with the address. The only care is to
1968 // to use the dummy character explicit length if any instead of the
1969 // actual argument length (that can be bigger).
1970 if (const Fortran::semantics::DeclTypeSpec *type = arg->GetType())
1971 if (type->category() == Fortran::semantics::DeclTypeSpec::Character)
1972 if (const Fortran::semantics::MaybeIntExpr &lenExpr =
1973 type->characterTypeSpec().length().GetExplicit()) {
1974 mlir::Value len = fir::getBase(genval(*lenExpr));
1975 // F2018 7.4.4.2 point 5.
1976 len = fir::factory::genMaxWithZero(builder, getLoc(), len);
1977 symMap.addSymbol(*arg,
1978 replaceScalarCharacterLength(gen(*expr), len));
1979 continue;
1981 symMap.addSymbol(*arg, gen(*expr));
1984 // Explicitly map statement function host associated symbols to their
1985 // parent scope lowered symbol box.
1986 for (const Fortran::semantics::SymbolRef &sym :
1987 Fortran::evaluate::CollectSymbols(*details.stmtFunction()))
1988 if (const auto *details =
1989 sym->detailsIf<Fortran::semantics::HostAssocDetails>())
1990 if (!symMap.lookupSymbol(*sym))
1991 symMap.addSymbol(*sym, gen(details->symbol()));
1993 ExtValue result = genval(details.stmtFunction().value());
1994 LLVM_DEBUG(llvm::dbgs() << "stmt-function: " << result << '\n');
1995 symMap.popScope();
1996 return result;
1999 /// Create a contiguous temporary array with the same shape,
2000 /// length parameters and type as mold. It is up to the caller to deallocate
2001 /// the temporary.
2002 ExtValue genArrayTempFromMold(const ExtValue &mold,
2003 llvm::StringRef tempName) {
2004 mlir::Type type = fir::dyn_cast_ptrOrBoxEleTy(fir::getBase(mold).getType());
2005 assert(type && "expected descriptor or memory type");
2006 mlir::Location loc = getLoc();
2007 llvm::SmallVector<mlir::Value> extents =
2008 fir::factory::getExtents(loc, builder, mold);
2009 llvm::SmallVector<mlir::Value> allocMemTypeParams =
2010 fir::getTypeParams(mold);
2011 mlir::Value charLen;
2012 mlir::Type elementType = fir::unwrapSequenceType(type);
2013 if (auto charType = mlir::dyn_cast<fir::CharacterType>(elementType)) {
2014 charLen = allocMemTypeParams.empty()
2015 ? fir::factory::readCharLen(builder, loc, mold)
2016 : allocMemTypeParams[0];
2017 if (charType.hasDynamicLen() && allocMemTypeParams.empty())
2018 allocMemTypeParams.push_back(charLen);
2019 } else if (fir::hasDynamicSize(elementType)) {
2020 TODO(loc, "creating temporary for derived type with length parameters");
2023 mlir::Value temp = builder.create<fir::AllocMemOp>(
2024 loc, type, tempName, allocMemTypeParams, extents);
2025 if (mlir::isa<fir::CharacterType>(fir::unwrapSequenceType(type)))
2026 return fir::CharArrayBoxValue{temp, charLen, extents};
2027 return fir::ArrayBoxValue{temp, extents};
2030 /// Copy \p source array into \p dest array. Both arrays must be
2031 /// conforming, but neither array must be contiguous.
2032 void genArrayCopy(ExtValue dest, ExtValue source) {
2033 return createSomeArrayAssignment(converter, dest, source, symMap, stmtCtx);
2036 /// Lower a non-elemental procedure reference and read allocatable and pointer
2037 /// results into normal values.
2038 ExtValue genProcedureRef(const Fortran::evaluate::ProcedureRef &procRef,
2039 std::optional<mlir::Type> resultType) {
2040 ExtValue res = genRawProcedureRef(procRef, resultType);
2041 // In most contexts, pointers and allocatable do not appear as allocatable
2042 // or pointer variable on the caller side (see 8.5.3 note 1 for
2043 // allocatables). The few context where this can happen must call
2044 // genRawProcedureRef directly.
2045 if (const auto *box = res.getBoxOf<fir::MutableBoxValue>())
2046 return fir::factory::genMutableBoxRead(builder, getLoc(), *box);
2047 return res;
2050 /// Like genExtAddr, but ensure the address returned is a temporary even if \p
2051 /// expr is variable inside parentheses.
2052 ExtValue genTempExtAddr(const Fortran::lower::SomeExpr &expr) {
2053 // In general, genExtAddr might not create a temp for variable inside
2054 // parentheses to avoid creating array temporary in sub-expressions. It only
2055 // ensures the sub-expression is not re-associated with other parts of the
2056 // expression. In the call semantics, there is a difference between expr and
2057 // variable (see R1524). For expressions, a variable storage must not be
2058 // argument associated since it could be modified inside the call, or the
2059 // variable could also be modified by other means during the call.
2060 if (!isParenthesizedVariable(expr))
2061 return genExtAddr(expr);
2062 if (expr.Rank() > 0)
2063 return asArray(expr);
2064 mlir::Location loc = getLoc();
2065 return genExtValue(expr).match(
2066 [&](const fir::CharBoxValue &boxChar) -> ExtValue {
2067 return fir::factory::CharacterExprHelper{builder, loc}.createTempFrom(
2068 boxChar);
2070 [&](const fir::UnboxedValue &v) -> ExtValue {
2071 mlir::Type type = v.getType();
2072 mlir::Value value = v;
2073 if (fir::isa_ref_type(type))
2074 value = builder.create<fir::LoadOp>(loc, value);
2075 mlir::Value temp = builder.createTemporary(loc, value.getType());
2076 builder.create<fir::StoreOp>(loc, value, temp);
2077 return temp;
2079 [&](const fir::BoxValue &x) -> ExtValue {
2080 // Derived type scalar that may be polymorphic.
2081 if (fir::isPolymorphicType(fir::getBase(x).getType()))
2082 TODO(loc, "polymorphic array temporary");
2083 assert(!x.hasRank() && x.isDerived());
2084 if (x.isDerivedWithLenParameters())
2085 fir::emitFatalError(
2086 loc, "making temps for derived type with length parameters");
2087 // TODO: polymorphic aspects should be kept but for now the temp
2088 // created always has the declared type.
2089 mlir::Value var =
2090 fir::getBase(fir::factory::readBoxValue(builder, loc, x));
2091 auto value = builder.create<fir::LoadOp>(loc, var);
2092 mlir::Value temp = builder.createTemporary(loc, value.getType());
2093 builder.create<fir::StoreOp>(loc, value, temp);
2094 return temp;
2096 [&](const fir::PolymorphicValue &p) -> ExtValue {
2097 TODO(loc, "creating polymorphic temporary");
2099 [&](const auto &) -> ExtValue {
2100 fir::emitFatalError(loc, "expr is not a scalar value");
2104 /// Helper structure to track potential copy-in of non contiguous variable
2105 /// argument into a contiguous temp. It is used to deallocate the temp that
2106 /// may have been created as well as to the copy-out from the temp to the
2107 /// variable after the call.
2108 struct CopyOutPair {
2109 ExtValue var;
2110 ExtValue temp;
2111 // Flag to indicate if the argument may have been modified by the
2112 // callee, in which case it must be copied-out to the variable.
2113 bool argMayBeModifiedByCall;
2114 // Optional boolean value that, if present and false, prevents
2115 // the copy-out and temp deallocation.
2116 std::optional<mlir::Value> restrictCopyAndFreeAtRuntime;
2118 using CopyOutPairs = llvm::SmallVector<CopyOutPair, 4>;
2120 /// Helper to read any fir::BoxValue into other fir::ExtendedValue categories
2121 /// not based on fir.box.
2122 /// This will lose any non contiguous stride information and dynamic type and
2123 /// should only be called if \p exv is known to be contiguous or if its base
2124 /// address will be replaced by a contiguous one. If \p exv is not a
2125 /// fir::BoxValue, this is a no-op.
2126 ExtValue readIfBoxValue(const ExtValue &exv) {
2127 if (const auto *box = exv.getBoxOf<fir::BoxValue>())
2128 return fir::factory::readBoxValue(builder, getLoc(), *box);
2129 return exv;
2132 /// Generate a contiguous temp to pass \p actualArg as argument \p arg. The
2133 /// creation of the temp and copy-in can be made conditional at runtime by
2134 /// providing a runtime boolean flag \p restrictCopyAtRuntime (in which case
2135 /// the temp and copy will only be made if the value is true at runtime).
2136 ExtValue genCopyIn(const ExtValue &actualArg,
2137 const Fortran::lower::CallerInterface::PassedEntity &arg,
2138 CopyOutPairs &copyOutPairs,
2139 std::optional<mlir::Value> restrictCopyAtRuntime,
2140 bool byValue) {
2141 const bool doCopyOut = !byValue && arg.mayBeModifiedByCall();
2142 llvm::StringRef tempName = byValue ? ".copy" : ".copyinout";
2143 mlir::Location loc = getLoc();
2144 bool isActualArgBox = fir::isa_box_type(fir::getBase(actualArg).getType());
2145 mlir::Value isContiguousResult;
2146 mlir::Type addrType = fir::HeapType::get(
2147 fir::unwrapPassByRefType(fir::getBase(actualArg).getType()));
2149 if (isActualArgBox) {
2150 // Check at runtime if the argument is contiguous so no copy is needed.
2151 isContiguousResult =
2152 fir::runtime::genIsContiguous(builder, loc, fir::getBase(actualArg));
2155 auto doCopyIn = [&]() -> ExtValue {
2156 ExtValue temp = genArrayTempFromMold(actualArg, tempName);
2157 if (!arg.mayBeReadByCall() &&
2158 // INTENT(OUT) dummy argument finalization, automatically
2159 // done when the procedure is invoked, may imply reading
2160 // the argument value in the finalization routine.
2161 // So we need to make a copy, if finalization may occur.
2162 // TODO: do we have to avoid the copying for an actual
2163 // argument of type that does not require finalization?
2164 !arg.mayRequireIntentoutFinalization() &&
2165 // ALLOCATABLE dummy argument may require finalization.
2166 // If it has to be automatically deallocated at the end
2167 // of the procedure invocation (9.7.3.2 p. 2),
2168 // then the finalization may happen if the actual argument
2169 // is allocated (7.5.6.3 p. 2).
2170 !arg.hasAllocatableAttribute()) {
2171 // We have to initialize the temp if it may have components
2172 // that need initialization. If there are no components
2173 // requiring initialization, then the call is a no-op.
2174 if (mlir::isa<fir::RecordType>(getElementTypeOf(temp))) {
2175 mlir::Value tempBox = fir::getBase(builder.createBox(loc, temp));
2176 fir::runtime::genDerivedTypeInitialize(builder, loc, tempBox);
2178 return temp;
2180 if (!isActualArgBox || inlineCopyInOutForBoxes) {
2181 genArrayCopy(temp, actualArg);
2182 return temp;
2185 // Generate AssignTemporary() call to copy data from the actualArg
2186 // to a temporary. AssignTemporary() will initialize the temporary,
2187 // if needed, before doing the assignment, which is required
2188 // since the temporary's components (if any) are uninitialized
2189 // at this point.
2190 mlir::Value destBox = fir::getBase(builder.createBox(loc, temp));
2191 mlir::Value boxRef = builder.createTemporary(loc, destBox.getType());
2192 builder.create<fir::StoreOp>(loc, destBox, boxRef);
2193 fir::runtime::genAssignTemporary(builder, loc, boxRef,
2194 fir::getBase(actualArg));
2195 return temp;
2198 auto noCopy = [&]() {
2199 mlir::Value box = fir::getBase(actualArg);
2200 mlir::Value boxAddr = builder.create<fir::BoxAddrOp>(loc, addrType, box);
2201 builder.create<fir::ResultOp>(loc, boxAddr);
2204 auto combinedCondition = [&]() {
2205 if (isActualArgBox) {
2206 mlir::Value zero =
2207 builder.createIntegerConstant(loc, builder.getI1Type(), 0);
2208 mlir::Value notContiguous = builder.create<mlir::arith::CmpIOp>(
2209 loc, mlir::arith::CmpIPredicate::eq, isContiguousResult, zero);
2210 if (!restrictCopyAtRuntime) {
2211 restrictCopyAtRuntime = notContiguous;
2212 } else {
2213 mlir::Value cond = builder.create<mlir::arith::AndIOp>(
2214 loc, *restrictCopyAtRuntime, notContiguous);
2215 restrictCopyAtRuntime = cond;
2220 if (!restrictCopyAtRuntime) {
2221 if (isActualArgBox) {
2222 // isContiguousResult = genIsContiguousCall();
2223 mlir::Value addr =
2224 builder
2225 .genIfOp(loc, {addrType}, isContiguousResult,
2226 /*withElseRegion=*/true)
2227 .genThen([&]() { noCopy(); })
2228 .genElse([&] {
2229 ExtValue temp = doCopyIn();
2230 builder.create<fir::ResultOp>(loc, fir::getBase(temp));
2232 .getResults()[0];
2233 fir::ExtendedValue temp =
2234 fir::substBase(readIfBoxValue(actualArg), addr);
2235 combinedCondition();
2236 copyOutPairs.emplace_back(
2237 CopyOutPair{actualArg, temp, doCopyOut, restrictCopyAtRuntime});
2238 return temp;
2241 ExtValue temp = doCopyIn();
2242 copyOutPairs.emplace_back(CopyOutPair{actualArg, temp, doCopyOut, {}});
2243 return temp;
2246 // Otherwise, need to be careful to only copy-in if allowed at runtime.
2247 mlir::Value addr =
2248 builder
2249 .genIfOp(loc, {addrType}, *restrictCopyAtRuntime,
2250 /*withElseRegion=*/true)
2251 .genThen([&]() {
2252 if (isActualArgBox) {
2253 // isContiguousResult = genIsContiguousCall();
2254 // Avoid copyin if the argument is contiguous at runtime.
2255 mlir::Value addr1 =
2256 builder
2257 .genIfOp(loc, {addrType}, isContiguousResult,
2258 /*withElseRegion=*/true)
2259 .genThen([&]() { noCopy(); })
2260 .genElse([&]() {
2261 ExtValue temp = doCopyIn();
2262 builder.create<fir::ResultOp>(loc,
2263 fir::getBase(temp));
2265 .getResults()[0];
2266 builder.create<fir::ResultOp>(loc, addr1);
2267 } else {
2268 ExtValue temp = doCopyIn();
2269 builder.create<fir::ResultOp>(loc, fir::getBase(temp));
2272 .genElse([&]() {
2273 mlir::Value nullPtr = builder.createNullConstant(loc, addrType);
2274 builder.create<fir::ResultOp>(loc, nullPtr);
2276 .getResults()[0];
2277 // Associate the temp address with actualArg lengths and extents if a
2278 // temporary is generated. Otherwise the same address is associated.
2279 fir::ExtendedValue temp = fir::substBase(readIfBoxValue(actualArg), addr);
2280 combinedCondition();
2281 copyOutPairs.emplace_back(
2282 CopyOutPair{actualArg, temp, doCopyOut, restrictCopyAtRuntime});
2283 return temp;
2286 /// Generate copy-out if needed and free the temporary for an argument that
2287 /// has been copied-in into a contiguous temp.
2288 void genCopyOut(const CopyOutPair &copyOutPair) {
2289 mlir::Location loc = getLoc();
2290 bool isActualArgBox =
2291 fir::isa_box_type(fir::getBase(copyOutPair.var).getType());
2292 auto doCopyOut = [&]() {
2293 if (!isActualArgBox || inlineCopyInOutForBoxes) {
2294 if (copyOutPair.argMayBeModifiedByCall)
2295 genArrayCopy(copyOutPair.var, copyOutPair.temp);
2296 if (mlir::isa<fir::RecordType>(
2297 fir::getElementTypeOf(copyOutPair.temp))) {
2298 // Destroy components of the temporary (if any).
2299 // If there are no components requiring destruction, then the call
2300 // is a no-op.
2301 mlir::Value tempBox =
2302 fir::getBase(builder.createBox(loc, copyOutPair.temp));
2303 fir::runtime::genDerivedTypeDestroyWithoutFinalization(builder, loc,
2304 tempBox);
2306 // Deallocate the top-level entity of the temporary.
2307 builder.create<fir::FreeMemOp>(loc, fir::getBase(copyOutPair.temp));
2308 return;
2310 // Generate CopyOutAssign() call to copy data from the temporary
2311 // to the actualArg. Note that in case the actual argument
2312 // is ALLOCATABLE/POINTER the CopyOutAssign() implementation
2313 // should not engage its reallocation, because the temporary
2314 // is rank, shape and type compatible with it.
2315 // Moreover, CopyOutAssign() guarantees that there will be no
2316 // finalization for the LHS even if it is of a derived type
2317 // with finalization.
2319 // Create allocatable descriptor for the temp so that the runtime may
2320 // deallocate it.
2321 mlir::Value srcBox =
2322 fir::getBase(builder.createBox(loc, copyOutPair.temp));
2323 mlir::Type allocBoxTy =
2324 mlir::cast<fir::BaseBoxType>(srcBox.getType())
2325 .getBoxTypeWithNewAttr(fir::BaseBoxType::Attribute::Allocatable);
2326 srcBox = builder.create<fir::ReboxOp>(loc, allocBoxTy, srcBox,
2327 /*shift=*/mlir::Value{},
2328 /*slice=*/mlir::Value{});
2329 mlir::Value srcBoxRef = builder.createTemporary(loc, srcBox.getType());
2330 builder.create<fir::StoreOp>(loc, srcBox, srcBoxRef);
2331 // Create descriptor pointer to variable descriptor if copy out is needed,
2332 // and nullptr otherwise.
2333 mlir::Value destBoxRef;
2334 if (copyOutPair.argMayBeModifiedByCall) {
2335 mlir::Value destBox =
2336 fir::getBase(builder.createBox(loc, copyOutPair.var));
2337 destBoxRef = builder.createTemporary(loc, destBox.getType());
2338 builder.create<fir::StoreOp>(loc, destBox, destBoxRef);
2339 } else {
2340 destBoxRef = builder.create<fir::ZeroOp>(loc, srcBoxRef.getType());
2342 fir::runtime::genCopyOutAssign(builder, loc, destBoxRef, srcBoxRef);
2345 if (!copyOutPair.restrictCopyAndFreeAtRuntime)
2346 doCopyOut();
2347 else
2348 builder.genIfThen(loc, *copyOutPair.restrictCopyAndFreeAtRuntime)
2349 .genThen([&]() { doCopyOut(); })
2350 .end();
2353 /// Lower a designator to a variable that may be absent at runtime into an
2354 /// ExtendedValue where all the properties (base address, shape and length
2355 /// parameters) can be safely read (set to zero if not present). It also
2356 /// returns a boolean mlir::Value telling if the variable is present at
2357 /// runtime.
2358 /// This is useful to later be able to do conditional copy-in/copy-out
2359 /// or to retrieve the base address without having to deal with the case
2360 /// where the actual may be an absent fir.box.
2361 std::pair<ExtValue, mlir::Value>
2362 prepareActualThatMayBeAbsent(const Fortran::lower::SomeExpr &expr) {
2363 mlir::Location loc = getLoc();
2364 if (Fortran::evaluate::IsAllocatableOrPointerObject(expr)) {
2365 // Fortran 2018 15.5.2.12 point 1: If unallocated/disassociated,
2366 // it is as if the argument was absent. The main care here is to
2367 // not do a copy-in/copy-out because the temp address, even though
2368 // pointing to a null size storage, would not be a nullptr and
2369 // therefore the argument would not be considered absent on the
2370 // callee side. Note: if wholeSymbol is optional, it cannot be
2371 // absent as per 15.5.2.12 point 7. and 8. We rely on this to
2372 // un-conditionally read the allocatable/pointer descriptor here.
2373 fir::MutableBoxValue mutableBox = genMutableBoxValue(expr);
2374 mlir::Value isPresent = fir::factory::genIsAllocatedOrAssociatedTest(
2375 builder, loc, mutableBox);
2376 fir::ExtendedValue actualArg =
2377 fir::factory::genMutableBoxRead(builder, loc, mutableBox);
2378 return {actualArg, isPresent};
2380 // Absent descriptor cannot be read. To avoid any issue in
2381 // copy-in/copy-out, and when retrieving the address/length
2382 // create an descriptor pointing to a null address here if the
2383 // fir.box is absent.
2384 ExtValue actualArg = gen(expr);
2385 mlir::Value actualArgBase = fir::getBase(actualArg);
2386 mlir::Value isPresent = builder.create<fir::IsPresentOp>(
2387 loc, builder.getI1Type(), actualArgBase);
2388 if (!mlir::isa<fir::BoxType>(actualArgBase.getType()))
2389 return {actualArg, isPresent};
2390 ExtValue safeToReadBox =
2391 absentBoxToUnallocatedBox(builder, loc, actualArg, isPresent);
2392 return {safeToReadBox, isPresent};
2395 /// Create a temp on the stack for scalar actual arguments that may be absent
2396 /// at runtime, but must be passed via a temp if they are presents.
2397 fir::ExtendedValue
2398 createScalarTempForArgThatMayBeAbsent(ExtValue actualArg,
2399 mlir::Value isPresent) {
2400 mlir::Location loc = getLoc();
2401 mlir::Type type = fir::unwrapRefType(fir::getBase(actualArg).getType());
2402 if (fir::isDerivedWithLenParameters(actualArg))
2403 TODO(loc, "parametrized derived type optional scalar argument copy-in");
2404 if (const fir::CharBoxValue *charBox = actualArg.getCharBox()) {
2405 mlir::Value len = charBox->getLen();
2406 mlir::Value zero = builder.createIntegerConstant(loc, len.getType(), 0);
2407 len = builder.create<mlir::arith::SelectOp>(loc, isPresent, len, zero);
2408 mlir::Value temp =
2409 builder.createTemporary(loc, type, /*name=*/{},
2410 /*shape=*/{}, mlir::ValueRange{len},
2411 llvm::ArrayRef<mlir::NamedAttribute>{
2412 fir::getAdaptToByRefAttr(builder)});
2413 return fir::CharBoxValue{temp, len};
2415 assert((fir::isa_trivial(type) || mlir::isa<fir::RecordType>(type)) &&
2416 "must be simple scalar");
2417 return builder.createTemporary(loc, type,
2418 llvm::ArrayRef<mlir::NamedAttribute>{
2419 fir::getAdaptToByRefAttr(builder)});
2422 template <typename A>
2423 bool isCharacterType(const A &exp) {
2424 if (auto type = exp.GetType())
2425 return type->category() == Fortran::common::TypeCategory::Character;
2426 return false;
2429 /// Lower an actual argument that must be passed via an address.
2430 /// This generates of the copy-in/copy-out if the actual is not contiguous, or
2431 /// the creation of the temp if the actual is a variable and \p byValue is
2432 /// true. It handles the cases where the actual may be absent, and all of the
2433 /// copying has to be conditional at runtime.
2434 /// If the actual argument may be dynamically absent, return an additional
2435 /// boolean mlir::Value that if true means that the actual argument is
2436 /// present.
2437 std::pair<ExtValue, std::optional<mlir::Value>>
2438 prepareActualToBaseAddressLike(
2439 const Fortran::lower::SomeExpr &expr,
2440 const Fortran::lower::CallerInterface::PassedEntity &arg,
2441 CopyOutPairs &copyOutPairs, bool byValue) {
2442 mlir::Location loc = getLoc();
2443 const bool isArray = expr.Rank() > 0;
2444 const bool actualArgIsVariable = Fortran::evaluate::IsVariable(expr);
2445 // It must be possible to modify VALUE arguments on the callee side, even
2446 // if the actual argument is a literal or named constant. Hence, the
2447 // address of static storage must not be passed in that case, and a copy
2448 // must be made even if this is not a variable.
2449 // Note: isArray should be used here, but genBoxArg already creates copies
2450 // for it, so do not duplicate the copy until genBoxArg behavior is changed.
2451 const bool isStaticConstantByValue =
2452 byValue && Fortran::evaluate::IsActuallyConstant(expr) &&
2453 (isCharacterType(expr));
2454 const bool variableNeedsCopy =
2455 actualArgIsVariable &&
2456 (byValue || (isArray && !Fortran::evaluate::IsSimplyContiguous(
2457 expr, converter.getFoldingContext())));
2458 const bool needsCopy = isStaticConstantByValue || variableNeedsCopy;
2459 auto [argAddr, isPresent] =
2460 [&]() -> std::pair<ExtValue, std::optional<mlir::Value>> {
2461 if (!actualArgIsVariable && !needsCopy)
2462 // Actual argument is not a variable. Make sure a variable address is
2463 // not passed.
2464 return {genTempExtAddr(expr), std::nullopt};
2465 ExtValue baseAddr;
2466 if (arg.isOptional() &&
2467 Fortran::evaluate::MayBePassedAsAbsentOptional(expr)) {
2468 auto [actualArgBind, isPresent] = prepareActualThatMayBeAbsent(expr);
2469 const ExtValue &actualArg = actualArgBind;
2470 if (!needsCopy)
2471 return {actualArg, isPresent};
2473 if (isArray)
2474 return {genCopyIn(actualArg, arg, copyOutPairs, isPresent, byValue),
2475 isPresent};
2476 // Scalars, create a temp, and use it conditionally at runtime if
2477 // the argument is present.
2478 ExtValue temp =
2479 createScalarTempForArgThatMayBeAbsent(actualArg, isPresent);
2480 mlir::Type tempAddrTy = fir::getBase(temp).getType();
2481 mlir::Value selectAddr =
2482 builder
2483 .genIfOp(loc, {tempAddrTy}, isPresent,
2484 /*withElseRegion=*/true)
2485 .genThen([&]() {
2486 fir::factory::genScalarAssignment(builder, loc, temp,
2487 actualArg);
2488 builder.create<fir::ResultOp>(loc, fir::getBase(temp));
2490 .genElse([&]() {
2491 mlir::Value absent =
2492 builder.create<fir::AbsentOp>(loc, tempAddrTy);
2493 builder.create<fir::ResultOp>(loc, absent);
2495 .getResults()[0];
2496 return {fir::substBase(temp, selectAddr), isPresent};
2498 // Actual cannot be absent, the actual argument can safely be
2499 // copied-in/copied-out without any care if needed.
2500 if (isArray) {
2501 ExtValue box = genBoxArg(expr);
2502 if (needsCopy)
2503 return {genCopyIn(box, arg, copyOutPairs,
2504 /*restrictCopyAtRuntime=*/std::nullopt, byValue),
2505 std::nullopt};
2506 // Contiguous: just use the box we created above!
2507 // This gets "unboxed" below, if needed.
2508 return {box, std::nullopt};
2510 // Actual argument is a non-optional, non-pointer, non-allocatable
2511 // scalar.
2512 ExtValue actualArg = genExtAddr(expr);
2513 if (needsCopy)
2514 return {createInMemoryScalarCopy(builder, loc, actualArg),
2515 std::nullopt};
2516 return {actualArg, std::nullopt};
2517 }();
2518 // Scalar and contiguous expressions may be lowered to a fir.box,
2519 // either to account for potential polymorphism, or because lowering
2520 // did not account for some contiguity hints.
2521 // Here, polymorphism does not matter (an entity of the declared type
2522 // is passed, not one of the dynamic type), and the expr is known to
2523 // be simply contiguous, so it is safe to unbox it and pass the
2524 // address without making a copy.
2525 return {readIfBoxValue(argAddr), isPresent};
2528 /// Lower a non-elemental procedure reference.
2529 ExtValue genRawProcedureRef(const Fortran::evaluate::ProcedureRef &procRef,
2530 std::optional<mlir::Type> resultType) {
2531 mlir::Location loc = getLoc();
2532 if (isElementalProcWithArrayArgs(procRef))
2533 fir::emitFatalError(loc, "trying to lower elemental procedure with array "
2534 "arguments as normal procedure");
2536 if (const Fortran::evaluate::SpecificIntrinsic *intrinsic =
2537 procRef.proc().GetSpecificIntrinsic())
2538 return genIntrinsicRef(procRef, resultType, *intrinsic);
2540 if (Fortran::lower::isIntrinsicModuleProcRef(procRef) &&
2541 !Fortran::semantics::IsBindCProcedure(*procRef.proc().GetSymbol()))
2542 return genIntrinsicRef(procRef, resultType);
2544 if (isStatementFunctionCall(procRef))
2545 return genStmtFunctionRef(procRef);
2547 Fortran::lower::CallerInterface caller(procRef, converter);
2548 using PassBy = Fortran::lower::CallerInterface::PassEntityBy;
2550 llvm::SmallVector<fir::MutableBoxValue> mutableModifiedByCall;
2551 // List of <var, temp> where temp must be copied into var after the call.
2552 CopyOutPairs copyOutPairs;
2554 mlir::FunctionType callSiteType = caller.genFunctionType();
2556 // Lower the actual arguments and map the lowered values to the dummy
2557 // arguments.
2558 for (const Fortran::lower::CallInterface<
2559 Fortran::lower::CallerInterface>::PassedEntity &arg :
2560 caller.getPassedArguments()) {
2561 const auto *actual = arg.entity;
2562 mlir::Type argTy = callSiteType.getInput(arg.firArgument);
2563 if (!actual) {
2564 // Optional dummy argument for which there is no actual argument.
2565 caller.placeInput(arg, builder.genAbsentOp(loc, argTy));
2566 continue;
2568 const auto *expr = actual->UnwrapExpr();
2569 if (!expr)
2570 TODO(loc, "assumed type actual argument");
2572 if (arg.passBy == PassBy::Value) {
2573 ExtValue argVal = genval(*expr);
2574 if (!fir::isUnboxedValue(argVal))
2575 fir::emitFatalError(
2576 loc, "internal error: passing non trivial value by value");
2577 caller.placeInput(arg, fir::getBase(argVal));
2578 continue;
2581 if (arg.passBy == PassBy::MutableBox) {
2582 if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>(
2583 *expr)) {
2584 // If expr is NULL(), the mutableBox created must be a deallocated
2585 // pointer with the dummy argument characteristics (see table 16.5
2586 // in Fortran 2018 standard).
2587 // No length parameters are set for the created box because any non
2588 // deferred type parameters of the dummy will be evaluated on the
2589 // callee side, and it is illegal to use NULL without a MOLD if any
2590 // dummy length parameters are assumed.
2591 mlir::Type boxTy = fir::dyn_cast_ptrEleTy(argTy);
2592 assert(boxTy && mlir::isa<fir::BaseBoxType>(boxTy) &&
2593 "must be a fir.box type");
2594 mlir::Value boxStorage = builder.createTemporary(loc, boxTy);
2595 mlir::Value nullBox = fir::factory::createUnallocatedBox(
2596 builder, loc, boxTy, /*nonDeferredParams=*/{});
2597 builder.create<fir::StoreOp>(loc, nullBox, boxStorage);
2598 caller.placeInput(arg, boxStorage);
2599 continue;
2601 if (fir::isPointerType(argTy) &&
2602 !Fortran::evaluate::IsObjectPointer(*expr)) {
2603 // Passing a non POINTER actual argument to a POINTER dummy argument.
2604 // Create a pointer of the dummy argument type and assign the actual
2605 // argument to it.
2606 mlir::Value irBox =
2607 builder.createTemporary(loc, fir::unwrapRefType(argTy));
2608 // Non deferred parameters will be evaluated on the callee side.
2609 fir::MutableBoxValue pointer(irBox,
2610 /*nonDeferredParams=*/mlir::ValueRange{},
2611 /*mutableProperties=*/{});
2612 Fortran::lower::associateMutableBox(converter, loc, pointer, *expr,
2613 /*lbounds=*/std::nullopt,
2614 stmtCtx);
2615 caller.placeInput(arg, irBox);
2616 continue;
2618 // Passing a POINTER to a POINTER, or an ALLOCATABLE to an ALLOCATABLE.
2619 fir::MutableBoxValue mutableBox = genMutableBoxValue(*expr);
2620 if (fir::isAllocatableType(argTy) && arg.isIntentOut() &&
2621 Fortran::semantics::IsBindCProcedure(*procRef.proc().GetSymbol()))
2622 Fortran::lower::genDeallocateIfAllocated(converter, mutableBox, loc);
2623 mlir::Value irBox =
2624 fir::factory::getMutableIRBox(builder, loc, mutableBox);
2625 caller.placeInput(arg, irBox);
2626 if (arg.mayBeModifiedByCall())
2627 mutableModifiedByCall.emplace_back(std::move(mutableBox));
2628 continue;
2630 if (arg.passBy == PassBy::BaseAddress || arg.passBy == PassBy::BoxChar ||
2631 arg.passBy == PassBy::BaseAddressValueAttribute ||
2632 arg.passBy == PassBy::CharBoxValueAttribute) {
2633 const bool byValue = arg.passBy == PassBy::BaseAddressValueAttribute ||
2634 arg.passBy == PassBy::CharBoxValueAttribute;
2635 ExtValue argAddr =
2636 prepareActualToBaseAddressLike(*expr, arg, copyOutPairs, byValue)
2637 .first;
2638 if (arg.passBy == PassBy::BaseAddress ||
2639 arg.passBy == PassBy::BaseAddressValueAttribute) {
2640 caller.placeInput(arg, fir::getBase(argAddr));
2641 } else {
2642 assert(arg.passBy == PassBy::BoxChar ||
2643 arg.passBy == PassBy::CharBoxValueAttribute);
2644 auto helper = fir::factory::CharacterExprHelper{builder, loc};
2645 auto boxChar = argAddr.match(
2646 [&](const fir::CharBoxValue &x) -> mlir::Value {
2647 // If a character procedure was passed instead, handle the
2648 // mismatch.
2649 auto funcTy =
2650 mlir::dyn_cast<mlir::FunctionType>(x.getAddr().getType());
2651 if (funcTy && funcTy.getNumResults() == 1 &&
2652 mlir::isa<fir::BoxCharType>(funcTy.getResult(0))) {
2653 auto boxTy =
2654 mlir::cast<fir::BoxCharType>(funcTy.getResult(0));
2655 mlir::Value ref = builder.createConvert(
2656 loc, builder.getRefType(boxTy.getEleTy()), x.getAddr());
2657 auto len = builder.create<fir::UndefOp>(
2658 loc, builder.getCharacterLengthType());
2659 return builder.create<fir::EmboxCharOp>(loc, boxTy, ref, len);
2661 return helper.createEmbox(x);
2663 [&](const fir::CharArrayBoxValue &x) {
2664 return helper.createEmbox(x);
2666 [&](const auto &x) -> mlir::Value {
2667 // Fortran allows an actual argument of a completely different
2668 // type to be passed to a procedure expecting a CHARACTER in the
2669 // dummy argument position. When this happens, the data pointer
2670 // argument is simply assumed to point to CHARACTER data and the
2671 // LEN argument used is garbage. Simulate this behavior by
2672 // free-casting the base address to be a !fir.char reference and
2673 // setting the LEN argument to undefined. What could go wrong?
2674 auto dataPtr = fir::getBase(x);
2675 assert(!mlir::isa<fir::BoxType>(dataPtr.getType()));
2676 return builder.convertWithSemantics(
2677 loc, argTy, dataPtr,
2678 /*allowCharacterConversion=*/true);
2680 caller.placeInput(arg, boxChar);
2682 } else if (arg.passBy == PassBy::Box) {
2683 if (arg.mustBeMadeContiguous() &&
2684 !Fortran::evaluate::IsSimplyContiguous(
2685 *expr, converter.getFoldingContext())) {
2686 // If the expression is a PDT, or a polymorphic entity, or an assumed
2687 // rank, it cannot currently be safely handled by
2688 // prepareActualToBaseAddressLike that is intended to prepare
2689 // arguments that can be passed as simple base address.
2690 if (auto dynamicType = expr->GetType())
2691 if (dynamicType->IsPolymorphic())
2692 TODO(loc, "passing a polymorphic entity to an OPTIONAL "
2693 "CONTIGUOUS argument");
2694 if (fir::isRecordWithTypeParameters(
2695 fir::unwrapSequenceType(fir::unwrapPassByRefType(argTy))))
2696 TODO(loc, "passing to an OPTIONAL CONTIGUOUS derived type argument "
2697 "with length parameters");
2698 if (Fortran::evaluate::IsAssumedRank(*expr))
2699 TODO(loc, "passing an assumed rank entity to an OPTIONAL "
2700 "CONTIGUOUS argument");
2701 // Assumed shape VALUE are currently TODO in the call interface
2702 // lowering.
2703 const bool byValue = false;
2704 auto [argAddr, isPresentValue] =
2705 prepareActualToBaseAddressLike(*expr, arg, copyOutPairs, byValue);
2706 mlir::Value box = builder.createBox(loc, argAddr);
2707 if (isPresentValue) {
2708 mlir::Value convertedBox = builder.createConvert(loc, argTy, box);
2709 auto absent = builder.create<fir::AbsentOp>(loc, argTy);
2710 caller.placeInput(arg,
2711 builder.create<mlir::arith::SelectOp>(
2712 loc, *isPresentValue, convertedBox, absent));
2713 } else {
2714 caller.placeInput(arg, builder.createBox(loc, argAddr));
2717 } else if (arg.isOptional() &&
2718 Fortran::evaluate::IsAllocatableOrPointerObject(*expr)) {
2719 // Before lowering to an address, handle the allocatable/pointer
2720 // actual argument to optional fir.box dummy. It is legal to pass
2721 // unallocated/disassociated entity to an optional. In this case, an
2722 // absent fir.box must be created instead of a fir.box with a null
2723 // value (Fortran 2018 15.5.2.12 point 1).
2725 // Note that passing an absent allocatable to a non-allocatable
2726 // optional dummy argument is illegal (15.5.2.12 point 3 (8)). So
2727 // nothing has to be done to generate an absent argument in this case,
2728 // and it is OK to unconditionally read the mutable box here.
2729 fir::MutableBoxValue mutableBox = genMutableBoxValue(*expr);
2730 mlir::Value isAllocated =
2731 fir::factory::genIsAllocatedOrAssociatedTest(builder, loc,
2732 mutableBox);
2733 auto absent = builder.create<fir::AbsentOp>(loc, argTy);
2734 /// For now, assume it is not OK to pass the allocatable/pointer
2735 /// descriptor to a non pointer/allocatable dummy. That is a strict
2736 /// interpretation of 18.3.6 point 4 that stipulates the descriptor
2737 /// has the dummy attributes in BIND(C) contexts.
2738 mlir::Value box = builder.createBox(
2739 loc, fir::factory::genMutableBoxRead(builder, loc, mutableBox));
2741 // NULL() passed as argument is passed as a !fir.box<none>. Since
2742 // select op requires the same type for its two argument, convert
2743 // !fir.box<none> to !fir.class<none> when the argument is
2744 // polymorphic.
2745 if (fir::isBoxNone(box.getType()) && fir::isPolymorphicType(argTy)) {
2746 box = builder.createConvert(
2747 loc,
2748 fir::ClassType::get(mlir::NoneType::get(builder.getContext())),
2749 box);
2750 } else if (mlir::isa<fir::BoxType>(box.getType()) &&
2751 fir::isPolymorphicType(argTy)) {
2752 box = builder.create<fir::ReboxOp>(loc, argTy, box, mlir::Value{},
2753 /*slice=*/mlir::Value{});
2756 // Need the box types to be exactly similar for the selectOp.
2757 mlir::Value convertedBox = builder.createConvert(loc, argTy, box);
2758 caller.placeInput(arg, builder.create<mlir::arith::SelectOp>(
2759 loc, isAllocated, convertedBox, absent));
2760 } else {
2761 auto dynamicType = expr->GetType();
2762 mlir::Value box;
2764 // Special case when an intrinsic scalar variable is passed to a
2765 // function expecting an optional unlimited polymorphic dummy
2766 // argument.
2767 // The presence test needs to be performed before emboxing otherwise
2768 // the program will crash.
2769 if (dynamicType->category() !=
2770 Fortran::common::TypeCategory::Derived &&
2771 expr->Rank() == 0 && fir::isUnlimitedPolymorphicType(argTy) &&
2772 arg.isOptional()) {
2773 ExtValue opt = lowerIntrinsicArgumentAsInquired(*expr);
2774 mlir::Value isPresent = genActualIsPresentTest(builder, loc, opt);
2775 box =
2776 builder
2777 .genIfOp(loc, {argTy}, isPresent, /*withElseRegion=*/true)
2778 .genThen([&]() {
2779 auto boxed = builder.createBox(
2780 loc, genBoxArg(*expr), fir::isPolymorphicType(argTy));
2781 builder.create<fir::ResultOp>(loc, boxed);
2783 .genElse([&]() {
2784 auto absent =
2785 builder.create<fir::AbsentOp>(loc, argTy).getResult();
2786 builder.create<fir::ResultOp>(loc, absent);
2788 .getResults()[0];
2789 } else {
2790 // Make sure a variable address is only passed if the expression is
2791 // actually a variable.
2792 box = Fortran::evaluate::IsVariable(*expr)
2793 ? builder.createBox(loc, genBoxArg(*expr),
2794 fir::isPolymorphicType(argTy),
2795 fir::isAssumedType(argTy))
2796 : builder.createBox(getLoc(), genTempExtAddr(*expr),
2797 fir::isPolymorphicType(argTy),
2798 fir::isAssumedType(argTy));
2799 if (mlir::isa<fir::BoxType>(box.getType()) &&
2800 fir::isPolymorphicType(argTy) && !fir::isAssumedType(argTy)) {
2801 mlir::Type actualTy = argTy;
2802 if (Fortran::lower::isParentComponent(*expr))
2803 actualTy = fir::BoxType::get(converter.genType(*expr));
2804 // Rebox can only be performed on a present argument.
2805 if (arg.isOptional()) {
2806 mlir::Value isPresent =
2807 genActualIsPresentTest(builder, loc, box);
2808 box = builder
2809 .genIfOp(loc, {actualTy}, isPresent,
2810 /*withElseRegion=*/true)
2811 .genThen([&]() {
2812 auto rebox =
2813 builder
2814 .create<fir::ReboxOp>(
2815 loc, actualTy, box, mlir::Value{},
2816 /*slice=*/mlir::Value{})
2817 .getResult();
2818 builder.create<fir::ResultOp>(loc, rebox);
2820 .genElse([&]() {
2821 auto absent =
2822 builder.create<fir::AbsentOp>(loc, actualTy)
2823 .getResult();
2824 builder.create<fir::ResultOp>(loc, absent);
2826 .getResults()[0];
2827 } else {
2828 box = builder.create<fir::ReboxOp>(loc, actualTy, box,
2829 mlir::Value{},
2830 /*slice=*/mlir::Value{});
2832 } else if (Fortran::lower::isParentComponent(*expr)) {
2833 fir::ExtendedValue newExv =
2834 Fortran::lower::updateBoxForParentComponent(converter, box,
2835 *expr);
2836 box = fir::getBase(newExv);
2839 caller.placeInput(arg, box);
2841 } else if (arg.passBy == PassBy::AddressAndLength) {
2842 ExtValue argRef = genExtAddr(*expr);
2843 caller.placeAddressAndLengthInput(arg, fir::getBase(argRef),
2844 fir::getLen(argRef));
2845 } else if (arg.passBy == PassBy::CharProcTuple) {
2846 ExtValue argRef = genExtAddr(*expr);
2847 mlir::Value tuple = createBoxProcCharTuple(
2848 converter, argTy, fir::getBase(argRef), fir::getLen(argRef));
2849 caller.placeInput(arg, tuple);
2850 } else {
2851 TODO(loc, "pass by value in non elemental function call");
2855 ExtValue result =
2856 Fortran::lower::genCallOpAndResult(loc, converter, symMap, stmtCtx,
2857 caller, callSiteType, resultType)
2858 .first;
2860 // Sync pointers and allocatables that may have been modified during the
2861 // call.
2862 for (const auto &mutableBox : mutableModifiedByCall)
2863 fir::factory::syncMutableBoxFromIRBox(builder, loc, mutableBox);
2864 // Handle case where result was passed as argument
2866 // Copy-out temps that were created for non contiguous variable arguments if
2867 // needed.
2868 for (const auto &copyOutPair : copyOutPairs)
2869 genCopyOut(copyOutPair);
2871 return result;
2874 template <typename A>
2875 ExtValue genval(const Fortran::evaluate::FunctionRef<A> &funcRef) {
2876 ExtValue result = genFunctionRef(funcRef);
2877 if (result.rank() == 0 && fir::isa_ref_type(fir::getBase(result).getType()))
2878 return genLoad(result);
2879 return result;
2882 ExtValue genval(const Fortran::evaluate::ProcedureRef &procRef) {
2883 std::optional<mlir::Type> resTy;
2884 if (procRef.hasAlternateReturns())
2885 resTy = builder.getIndexType();
2886 return genProcedureRef(procRef, resTy);
2889 template <typename A>
2890 bool isScalar(const A &x) {
2891 return x.Rank() == 0;
2894 /// Helper to detect Transformational function reference.
2895 template <typename T>
2896 bool isTransformationalRef(const T &) {
2897 return false;
2899 template <typename T>
2900 bool isTransformationalRef(const Fortran::evaluate::FunctionRef<T> &funcRef) {
2901 return !funcRef.IsElemental() && funcRef.Rank();
2903 template <typename T>
2904 bool isTransformationalRef(Fortran::evaluate::Expr<T> expr) {
2905 return Fortran::common::visit(
2906 [&](const auto &e) { return isTransformationalRef(e); }, expr.u);
2909 template <typename A>
2910 ExtValue asArray(const A &x) {
2911 return Fortran::lower::createSomeArrayTempValue(converter, toEvExpr(x),
2912 symMap, stmtCtx);
2915 /// Lower an array value as an argument. This argument can be passed as a box
2916 /// value, so it may be possible to avoid making a temporary.
2917 template <typename A>
2918 ExtValue asArrayArg(const Fortran::evaluate::Expr<A> &x) {
2919 return Fortran::common::visit(
2920 [&](const auto &e) { return asArrayArg(e, x); }, x.u);
2922 template <typename A, typename B>
2923 ExtValue asArrayArg(const Fortran::evaluate::Expr<A> &x, const B &y) {
2924 return Fortran::common::visit(
2925 [&](const auto &e) { return asArrayArg(e, y); }, x.u);
2927 template <typename A, typename B>
2928 ExtValue asArrayArg(const Fortran::evaluate::Designator<A> &, const B &x) {
2929 // Designator is being passed as an argument to a procedure. Lower the
2930 // expression to a boxed value.
2931 auto someExpr = toEvExpr(x);
2932 return Fortran::lower::createBoxValue(getLoc(), converter, someExpr, symMap,
2933 stmtCtx);
2935 template <typename A, typename B>
2936 ExtValue asArrayArg(const A &, const B &x) {
2937 // If the expression to pass as an argument is not a designator, then create
2938 // an array temp.
2939 return asArray(x);
2942 template <typename A>
2943 mlir::Value getIfOverridenExpr(const Fortran::evaluate::Expr<A> &x) {
2944 if (const Fortran::lower::ExprToValueMap *map =
2945 converter.getExprOverrides()) {
2946 Fortran::lower::SomeExpr someExpr = toEvExpr(x);
2947 if (auto match = map->find(&someExpr); match != map->end())
2948 return match->second;
2950 return mlir::Value{};
2953 template <typename A>
2954 ExtValue gen(const Fortran::evaluate::Expr<A> &x) {
2955 if (mlir::Value val = getIfOverridenExpr(x))
2956 return val;
2957 // Whole array symbols or components, and results of transformational
2958 // functions already have a storage and the scalar expression lowering path
2959 // is used to not create a new temporary storage.
2960 if (isScalar(x) ||
2961 Fortran::evaluate::UnwrapWholeSymbolOrComponentDataRef(x) ||
2962 (isTransformationalRef(x) && !isOptimizableTranspose(x, converter)))
2963 return Fortran::common::visit([&](const auto &e) { return genref(e); },
2964 x.u);
2965 if (useBoxArg)
2966 return asArrayArg(x);
2967 return asArray(x);
2969 template <typename A>
2970 ExtValue genval(const Fortran::evaluate::Expr<A> &x) {
2971 if (mlir::Value val = getIfOverridenExpr(x))
2972 return val;
2973 if (isScalar(x) || Fortran::evaluate::UnwrapWholeSymbolDataRef(x) ||
2974 inInitializer)
2975 return Fortran::common::visit([&](const auto &e) { return genval(e); },
2976 x.u);
2977 return asArray(x);
2980 template <int KIND>
2981 ExtValue genval(const Fortran::evaluate::Expr<Fortran::evaluate::Type<
2982 Fortran::common::TypeCategory::Logical, KIND>> &exp) {
2983 if (mlir::Value val = getIfOverridenExpr(exp))
2984 return val;
2985 return Fortran::common::visit([&](const auto &e) { return genval(e); },
2986 exp.u);
2989 using RefSet =
2990 std::tuple<Fortran::evaluate::ComplexPart, Fortran::evaluate::Substring,
2991 Fortran::evaluate::DataRef, Fortran::evaluate::Component,
2992 Fortran::evaluate::ArrayRef, Fortran::evaluate::CoarrayRef,
2993 Fortran::semantics::SymbolRef>;
2994 template <typename A>
2995 static constexpr bool inRefSet = Fortran::common::HasMember<A, RefSet>;
2997 template <typename A, typename = std::enable_if_t<inRefSet<A>>>
2998 ExtValue genref(const A &a) {
2999 return gen(a);
3001 template <typename A>
3002 ExtValue genref(const A &a) {
3003 if (inInitializer) {
3004 // Initialization expressions can never allocate memory.
3005 return genval(a);
3007 mlir::Type storageType = converter.genType(toEvExpr(a));
3008 return placeScalarValueInMemory(builder, getLoc(), genval(a), storageType);
3011 template <typename A, template <typename> typename T,
3012 typename B = std::decay_t<T<A>>,
3013 std::enable_if_t<
3014 std::is_same_v<B, Fortran::evaluate::Expr<A>> ||
3015 std::is_same_v<B, Fortran::evaluate::Designator<A>> ||
3016 std::is_same_v<B, Fortran::evaluate::FunctionRef<A>>,
3017 bool> = true>
3018 ExtValue genref(const T<A> &x) {
3019 return gen(x);
3022 private:
3023 mlir::Location location;
3024 Fortran::lower::AbstractConverter &converter;
3025 fir::FirOpBuilder &builder;
3026 Fortran::lower::StatementContext &stmtCtx;
3027 Fortran::lower::SymMap &symMap;
3028 bool inInitializer = false;
3029 bool useBoxArg = false; // expression lowered as argument
3031 } // namespace
3033 #define CONCAT(x, y) CONCAT2(x, y)
3034 #define CONCAT2(x, y) x##y
3036 // Helper for changing the semantics in a given context. Preserves the current
3037 // semantics which is resumed when the "push" goes out of scope.
3038 #define PushSemantics(PushVal) \
3039 [[maybe_unused]] auto CONCAT(pushSemanticsLocalVariable, __LINE__) = \
3040 Fortran::common::ScopedSet(semant, PushVal);
3042 static bool isAdjustedArrayElementType(mlir::Type t) {
3043 return fir::isa_char(t) || fir::isa_derived(t) ||
3044 mlir::isa<fir::SequenceType>(t);
3046 static bool elementTypeWasAdjusted(mlir::Type t) {
3047 if (auto ty = mlir::dyn_cast<fir::ReferenceType>(t))
3048 return isAdjustedArrayElementType(ty.getEleTy());
3049 return false;
3051 static mlir::Type adjustedArrayElementType(mlir::Type t) {
3052 return isAdjustedArrayElementType(t) ? fir::ReferenceType::get(t) : t;
3055 /// Helper to generate calls to scalar user defined assignment procedures.
3056 static void genScalarUserDefinedAssignmentCall(fir::FirOpBuilder &builder,
3057 mlir::Location loc,
3058 mlir::func::FuncOp func,
3059 const fir::ExtendedValue &lhs,
3060 const fir::ExtendedValue &rhs) {
3061 auto prepareUserDefinedArg =
3062 [](fir::FirOpBuilder &builder, mlir::Location loc,
3063 const fir::ExtendedValue &value, mlir::Type argType) -> mlir::Value {
3064 if (mlir::isa<fir::BoxCharType>(argType)) {
3065 const fir::CharBoxValue *charBox = value.getCharBox();
3066 assert(charBox && "argument type mismatch in elemental user assignment");
3067 return fir::factory::CharacterExprHelper{builder, loc}.createEmbox(
3068 *charBox);
3070 if (mlir::isa<fir::BaseBoxType>(argType)) {
3071 mlir::Value box =
3072 builder.createBox(loc, value, mlir::isa<fir::ClassType>(argType));
3073 return builder.createConvert(loc, argType, box);
3075 // Simple pass by address.
3076 mlir::Type argBaseType = fir::unwrapRefType(argType);
3077 assert(!fir::hasDynamicSize(argBaseType));
3078 mlir::Value from = fir::getBase(value);
3079 if (argBaseType != fir::unwrapRefType(from.getType())) {
3080 // With logicals, it is possible that from is i1 here.
3081 if (fir::isa_ref_type(from.getType()))
3082 from = builder.create<fir::LoadOp>(loc, from);
3083 from = builder.createConvert(loc, argBaseType, from);
3085 if (!fir::isa_ref_type(from.getType())) {
3086 mlir::Value temp = builder.createTemporary(loc, argBaseType);
3087 builder.create<fir::StoreOp>(loc, from, temp);
3088 from = temp;
3090 return builder.createConvert(loc, argType, from);
3092 assert(func.getNumArguments() == 2);
3093 mlir::Type lhsType = func.getFunctionType().getInput(0);
3094 mlir::Type rhsType = func.getFunctionType().getInput(1);
3095 mlir::Value lhsArg = prepareUserDefinedArg(builder, loc, lhs, lhsType);
3096 mlir::Value rhsArg = prepareUserDefinedArg(builder, loc, rhs, rhsType);
3097 builder.create<fir::CallOp>(loc, func, mlir::ValueRange{lhsArg, rhsArg});
3100 /// Convert the result of a fir.array_modify to an ExtendedValue given the
3101 /// related fir.array_load.
3102 static fir::ExtendedValue arrayModifyToExv(fir::FirOpBuilder &builder,
3103 mlir::Location loc,
3104 fir::ArrayLoadOp load,
3105 mlir::Value elementAddr) {
3106 mlir::Type eleTy = fir::unwrapPassByRefType(elementAddr.getType());
3107 if (fir::isa_char(eleTy)) {
3108 auto len = fir::factory::CharacterExprHelper{builder, loc}.getLength(
3109 load.getMemref());
3110 if (!len) {
3111 assert(load.getTypeparams().size() == 1 &&
3112 "length must be in array_load");
3113 len = load.getTypeparams()[0];
3115 return fir::CharBoxValue{elementAddr, len};
3117 return elementAddr;
3120 //===----------------------------------------------------------------------===//
3122 // Lowering of scalar expressions in an explicit iteration space context.
3124 //===----------------------------------------------------------------------===//
3126 // Shared code for creating a copy of a derived type element. This function is
3127 // called from a continuation.
3128 inline static fir::ArrayAmendOp
3129 createDerivedArrayAmend(mlir::Location loc, fir::ArrayLoadOp destLoad,
3130 fir::FirOpBuilder &builder, fir::ArrayAccessOp destAcc,
3131 const fir::ExtendedValue &elementExv, mlir::Type eleTy,
3132 mlir::Value innerArg) {
3133 if (destLoad.getTypeparams().empty()) {
3134 fir::factory::genRecordAssignment(builder, loc, destAcc, elementExv);
3135 } else {
3136 auto boxTy = fir::BoxType::get(eleTy);
3137 auto toBox = builder.create<fir::EmboxOp>(loc, boxTy, destAcc.getResult(),
3138 mlir::Value{}, mlir::Value{},
3139 destLoad.getTypeparams());
3140 auto fromBox = builder.create<fir::EmboxOp>(
3141 loc, boxTy, fir::getBase(elementExv), mlir::Value{}, mlir::Value{},
3142 destLoad.getTypeparams());
3143 fir::factory::genRecordAssignment(builder, loc, fir::BoxValue(toBox),
3144 fir::BoxValue(fromBox));
3146 return builder.create<fir::ArrayAmendOp>(loc, innerArg.getType(), innerArg,
3147 destAcc);
3150 inline static fir::ArrayAmendOp
3151 createCharArrayAmend(mlir::Location loc, fir::FirOpBuilder &builder,
3152 fir::ArrayAccessOp dstOp, mlir::Value &dstLen,
3153 const fir::ExtendedValue &srcExv, mlir::Value innerArg,
3154 llvm::ArrayRef<mlir::Value> bounds) {
3155 fir::CharBoxValue dstChar(dstOp, dstLen);
3156 fir::factory::CharacterExprHelper helper{builder, loc};
3157 if (!bounds.empty()) {
3158 dstChar = helper.createSubstring(dstChar, bounds);
3159 fir::factory::genCharacterCopy(fir::getBase(srcExv), fir::getLen(srcExv),
3160 dstChar.getAddr(), dstChar.getLen(), builder,
3161 loc);
3162 // Update the LEN to the substring's LEN.
3163 dstLen = dstChar.getLen();
3165 // For a CHARACTER, we generate the element assignment loops inline.
3166 helper.createAssign(fir::ExtendedValue{dstChar}, srcExv);
3167 // Mark this array element as amended.
3168 mlir::Type ty = innerArg.getType();
3169 auto amend = builder.create<fir::ArrayAmendOp>(loc, ty, innerArg, dstOp);
3170 return amend;
3173 /// Build an ExtendedValue from a fir.array<?x...?xT> without actually setting
3174 /// the actual extents and lengths. This is only to allow their propagation as
3175 /// ExtendedValue without triggering verifier failures when propagating
3176 /// character/arrays as unboxed values. Only the base of the resulting
3177 /// ExtendedValue should be used, it is undefined to use the length or extents
3178 /// of the extended value returned,
3179 inline static fir::ExtendedValue
3180 convertToArrayBoxValue(mlir::Location loc, fir::FirOpBuilder &builder,
3181 mlir::Value val, mlir::Value len) {
3182 mlir::Type ty = fir::unwrapRefType(val.getType());
3183 mlir::IndexType idxTy = builder.getIndexType();
3184 auto seqTy = mlir::cast<fir::SequenceType>(ty);
3185 auto undef = builder.create<fir::UndefOp>(loc, idxTy);
3186 llvm::SmallVector<mlir::Value> extents(seqTy.getDimension(), undef);
3187 if (fir::isa_char(seqTy.getEleTy()))
3188 return fir::CharArrayBoxValue(val, len ? len : undef, extents);
3189 return fir::ArrayBoxValue(val, extents);
3192 //===----------------------------------------------------------------------===//
3194 // Lowering of array expressions.
3196 //===----------------------------------------------------------------------===//
3198 namespace {
3199 class ArrayExprLowering {
3200 using ExtValue = fir::ExtendedValue;
3202 /// Structure to keep track of lowered array operands in the
3203 /// array expression. Useful to later deduce the shape of the
3204 /// array expression.
3205 struct ArrayOperand {
3206 /// Array base (can be a fir.box).
3207 mlir::Value memref;
3208 /// ShapeOp, ShapeShiftOp or ShiftOp
3209 mlir::Value shape;
3210 /// SliceOp
3211 mlir::Value slice;
3212 /// Can this operand be absent ?
3213 bool mayBeAbsent = false;
3216 using ImplicitSubscripts = Fortran::lower::details::ImplicitSubscripts;
3217 using PathComponent = Fortran::lower::PathComponent;
3219 /// Active iteration space.
3220 using IterationSpace = Fortran::lower::IterationSpace;
3221 using IterSpace = const Fortran::lower::IterationSpace &;
3223 /// Current continuation. Function that will generate IR for a single
3224 /// iteration of the pending iterative loop structure.
3225 using CC = Fortran::lower::GenerateElementalArrayFunc;
3227 /// Projection continuation. Function that will project one iteration space
3228 /// into another.
3229 using PC = std::function<IterationSpace(IterSpace)>;
3230 using ArrayBaseTy =
3231 std::variant<std::monostate, const Fortran::evaluate::ArrayRef *,
3232 const Fortran::evaluate::DataRef *>;
3233 using ComponentPath = Fortran::lower::ComponentPath;
3235 public:
3236 //===--------------------------------------------------------------------===//
3237 // Regular array assignment
3238 //===--------------------------------------------------------------------===//
3240 /// Entry point for array assignments. Both the left-hand and right-hand sides
3241 /// can either be ExtendedValue or evaluate::Expr.
3242 template <typename TL, typename TR>
3243 static void lowerArrayAssignment(Fortran::lower::AbstractConverter &converter,
3244 Fortran::lower::SymMap &symMap,
3245 Fortran::lower::StatementContext &stmtCtx,
3246 const TL &lhs, const TR &rhs) {
3247 ArrayExprLowering ael(converter, stmtCtx, symMap,
3248 ConstituentSemantics::CopyInCopyOut);
3249 ael.lowerArrayAssignment(lhs, rhs);
3252 template <typename TL, typename TR>
3253 void lowerArrayAssignment(const TL &lhs, const TR &rhs) {
3254 mlir::Location loc = getLoc();
3255 /// Here the target subspace is not necessarily contiguous. The ArrayUpdate
3256 /// continuation is implicitly returned in `ccStoreToDest` and the ArrayLoad
3257 /// in `destination`.
3258 PushSemantics(ConstituentSemantics::ProjectedCopyInCopyOut);
3259 ccStoreToDest = genarr(lhs);
3260 determineShapeOfDest(lhs);
3261 semant = ConstituentSemantics::RefTransparent;
3262 ExtValue exv = lowerArrayExpression(rhs);
3263 if (explicitSpaceIsActive()) {
3264 explicitSpace->finalizeContext();
3265 builder.create<fir::ResultOp>(loc, fir::getBase(exv));
3266 } else {
3267 builder.create<fir::ArrayMergeStoreOp>(
3268 loc, destination, fir::getBase(exv), destination.getMemref(),
3269 destination.getSlice(), destination.getTypeparams());
3273 //===--------------------------------------------------------------------===//
3274 // WHERE array assignment, FORALL assignment, and FORALL+WHERE array
3275 // assignment
3276 //===--------------------------------------------------------------------===//
3278 /// Entry point for array assignment when the iteration space is explicitly
3279 /// defined (Fortran's FORALL) with or without masks, and/or the implied
3280 /// iteration space involves masks (Fortran's WHERE). Both contexts (explicit
3281 /// space and implicit space with masks) may be present.
3282 static void lowerAnyMaskedArrayAssignment(
3283 Fortran::lower::AbstractConverter &converter,
3284 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx,
3285 const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs,
3286 Fortran::lower::ExplicitIterSpace &explicitSpace,
3287 Fortran::lower::ImplicitIterSpace &implicitSpace) {
3288 if (explicitSpace.isActive() && lhs.Rank() == 0) {
3289 // Scalar assignment expression in a FORALL context.
3290 ArrayExprLowering ael(converter, stmtCtx, symMap,
3291 ConstituentSemantics::RefTransparent,
3292 &explicitSpace, &implicitSpace);
3293 ael.lowerScalarAssignment(lhs, rhs);
3294 return;
3296 // Array assignment expression in a FORALL and/or WHERE context.
3297 ArrayExprLowering ael(converter, stmtCtx, symMap,
3298 ConstituentSemantics::CopyInCopyOut, &explicitSpace,
3299 &implicitSpace);
3300 ael.lowerArrayAssignment(lhs, rhs);
3303 //===--------------------------------------------------------------------===//
3304 // Array assignment to array of pointer box values.
3305 //===--------------------------------------------------------------------===//
3307 /// Entry point for assignment to pointer in an array of pointers.
3308 static void lowerArrayOfPointerAssignment(
3309 Fortran::lower::AbstractConverter &converter,
3310 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx,
3311 const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs,
3312 Fortran::lower::ExplicitIterSpace &explicitSpace,
3313 Fortran::lower::ImplicitIterSpace &implicitSpace,
3314 const llvm::SmallVector<mlir::Value> &lbounds,
3315 std::optional<llvm::SmallVector<mlir::Value>> ubounds) {
3316 ArrayExprLowering ael(converter, stmtCtx, symMap,
3317 ConstituentSemantics::CopyInCopyOut, &explicitSpace,
3318 &implicitSpace);
3319 ael.lowerArrayOfPointerAssignment(lhs, rhs, lbounds, ubounds);
3322 /// Scalar pointer assignment in an explicit iteration space.
3324 /// Pointers may be bound to targets in a FORALL context. This is a scalar
3325 /// assignment in the sense there is never an implied iteration space, even if
3326 /// the pointer is to a target with non-zero rank. Since the pointer
3327 /// assignment must appear in a FORALL construct, correctness may require that
3328 /// the array of pointers follow copy-in/copy-out semantics. The pointer
3329 /// assignment may include a bounds-spec (lower bounds), a bounds-remapping
3330 /// (lower and upper bounds), or neither.
3331 void lowerArrayOfPointerAssignment(
3332 const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs,
3333 const llvm::SmallVector<mlir::Value> &lbounds,
3334 std::optional<llvm::SmallVector<mlir::Value>> ubounds) {
3335 setPointerAssignmentBounds(lbounds, ubounds);
3336 if (rhs.Rank() == 0 ||
3337 (Fortran::evaluate::UnwrapWholeSymbolOrComponentDataRef(rhs) &&
3338 Fortran::evaluate::IsAllocatableOrPointerObject(rhs))) {
3339 lowerScalarAssignment(lhs, rhs);
3340 return;
3342 TODO(getLoc(),
3343 "auto boxing of a ranked expression on RHS for pointer assignment");
3346 //===--------------------------------------------------------------------===//
3347 // Array assignment to allocatable array
3348 //===--------------------------------------------------------------------===//
3350 /// Entry point for assignment to allocatable array.
3351 static void lowerAllocatableArrayAssignment(
3352 Fortran::lower::AbstractConverter &converter,
3353 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx,
3354 const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs,
3355 Fortran::lower::ExplicitIterSpace &explicitSpace,
3356 Fortran::lower::ImplicitIterSpace &implicitSpace) {
3357 ArrayExprLowering ael(converter, stmtCtx, symMap,
3358 ConstituentSemantics::CopyInCopyOut, &explicitSpace,
3359 &implicitSpace);
3360 ael.lowerAllocatableArrayAssignment(lhs, rhs);
3363 /// Lower an assignment to allocatable array, where the LHS array
3364 /// is represented with \p lhs extended value produced in different
3365 /// branches created in genReallocIfNeeded(). The RHS lowering
3366 /// is provided via \p rhsCC continuation.
3367 void lowerAllocatableArrayAssignment(ExtValue lhs, CC rhsCC) {
3368 mlir::Location loc = getLoc();
3369 // Check if the initial destShape is null, which means
3370 // it has not been computed from rhs (e.g. rhs is scalar).
3371 bool destShapeIsEmpty = destShape.empty();
3372 // Create ArrayLoad for the mutable box and save it into `destination`.
3373 PushSemantics(ConstituentSemantics::ProjectedCopyInCopyOut);
3374 ccStoreToDest = genarr(lhs);
3375 // destShape is either non-null on entry to this function,
3376 // or has been just set by lhs lowering.
3377 assert(!destShape.empty() && "destShape must have been set.");
3378 // Finish lowering the loop nest.
3379 assert(destination && "destination must have been set");
3380 ExtValue exv = lowerArrayExpression(rhsCC, destination.getType());
3381 if (!explicitSpaceIsActive())
3382 builder.create<fir::ArrayMergeStoreOp>(
3383 loc, destination, fir::getBase(exv), destination.getMemref(),
3384 destination.getSlice(), destination.getTypeparams());
3385 // destShape may originally be null, if rhs did not define a shape.
3386 // In this case the destShape is computed from lhs, and we may have
3387 // multiple different lhs values for different branches created
3388 // in genReallocIfNeeded(). We cannot reuse destShape computed
3389 // in different branches, so we have to reset it,
3390 // so that it is recomputed for the next branch FIR generation.
3391 if (destShapeIsEmpty)
3392 destShape.clear();
3395 /// Assignment to allocatable array.
3397 /// The semantics are reverse that of a "regular" array assignment. The rhs
3398 /// defines the iteration space of the computation and the lhs is
3399 /// resized/reallocated to fit if necessary.
3400 void lowerAllocatableArrayAssignment(const Fortran::lower::SomeExpr &lhs,
3401 const Fortran::lower::SomeExpr &rhs) {
3402 // With assignment to allocatable, we want to lower the rhs first and use
3403 // its shape to determine if we need to reallocate, etc.
3404 mlir::Location loc = getLoc();
3405 // FIXME: If the lhs is in an explicit iteration space, the assignment may
3406 // be to an array of allocatable arrays rather than a single allocatable
3407 // array.
3408 if (explicitSpaceIsActive() && lhs.Rank() > 0)
3409 TODO(loc, "assignment to whole allocatable array inside FORALL");
3411 fir::MutableBoxValue mutableBox =
3412 Fortran::lower::createMutableBox(loc, converter, lhs, symMap);
3413 if (rhs.Rank() > 0)
3414 determineShapeOfDest(rhs);
3415 auto rhsCC = [&]() {
3416 PushSemantics(ConstituentSemantics::RefTransparent);
3417 return genarr(rhs);
3418 }();
3420 llvm::SmallVector<mlir::Value> lengthParams;
3421 // Currently no safe way to gather length from rhs (at least for
3422 // character, it cannot be taken from array_loads since it may be
3423 // changed by concatenations).
3424 if ((mutableBox.isCharacter() && !mutableBox.hasNonDeferredLenParams()) ||
3425 mutableBox.isDerivedWithLenParameters())
3426 TODO(loc, "gather rhs LEN parameters in assignment to allocatable");
3428 // The allocatable must take lower bounds from the expr if it is
3429 // reallocated and the right hand side is not a scalar.
3430 const bool takeLboundsIfRealloc = rhs.Rank() > 0;
3431 llvm::SmallVector<mlir::Value> lbounds;
3432 // When the reallocated LHS takes its lower bounds from the RHS,
3433 // they will be non default only if the RHS is a whole array
3434 // variable. Otherwise, lbounds is left empty and default lower bounds
3435 // will be used.
3436 if (takeLboundsIfRealloc &&
3437 Fortran::evaluate::UnwrapWholeSymbolOrComponentDataRef(rhs)) {
3438 assert(arrayOperands.size() == 1 &&
3439 "lbounds can only come from one array");
3440 auto lbs = fir::factory::getOrigins(arrayOperands[0].shape);
3441 lbounds.append(lbs.begin(), lbs.end());
3443 auto assignToStorage = [&](fir::ExtendedValue newLhs) {
3444 // The lambda will be called repeatedly by genReallocIfNeeded().
3445 lowerAllocatableArrayAssignment(newLhs, rhsCC);
3447 fir::factory::MutableBoxReallocation realloc =
3448 fir::factory::genReallocIfNeeded(builder, loc, mutableBox, destShape,
3449 lengthParams, assignToStorage);
3450 if (explicitSpaceIsActive()) {
3451 explicitSpace->finalizeContext();
3452 builder.create<fir::ResultOp>(loc, fir::getBase(realloc.newValue));
3454 fir::factory::finalizeRealloc(builder, loc, mutableBox, lbounds,
3455 takeLboundsIfRealloc, realloc);
3458 /// Entry point for when an array expression appears in a context where the
3459 /// result must be boxed. (BoxValue semantics.)
3460 static ExtValue
3461 lowerBoxedArrayExpression(Fortran::lower::AbstractConverter &converter,
3462 Fortran::lower::SymMap &symMap,
3463 Fortran::lower::StatementContext &stmtCtx,
3464 const Fortran::lower::SomeExpr &expr) {
3465 ArrayExprLowering ael{converter, stmtCtx, symMap,
3466 ConstituentSemantics::BoxValue};
3467 return ael.lowerBoxedArrayExpr(expr);
3470 ExtValue lowerBoxedArrayExpr(const Fortran::lower::SomeExpr &exp) {
3471 PushSemantics(ConstituentSemantics::BoxValue);
3472 return Fortran::common::visit(
3473 [&](const auto &e) {
3474 auto f = genarr(e);
3475 ExtValue exv = f(IterationSpace{});
3476 if (mlir::isa<fir::BaseBoxType>(fir::getBase(exv).getType()))
3477 return exv;
3478 fir::emitFatalError(getLoc(), "array must be emboxed");
3480 exp.u);
3483 /// Entry point into lowering an expression with rank. This entry point is for
3484 /// lowering a rhs expression, for example. (RefTransparent semantics.)
3485 static ExtValue
3486 lowerNewArrayExpression(Fortran::lower::AbstractConverter &converter,
3487 Fortran::lower::SymMap &symMap,
3488 Fortran::lower::StatementContext &stmtCtx,
3489 const Fortran::lower::SomeExpr &expr) {
3490 ArrayExprLowering ael{converter, stmtCtx, symMap};
3491 ael.determineShapeOfDest(expr);
3492 ExtValue loopRes = ael.lowerArrayExpression(expr);
3493 fir::ArrayLoadOp dest = ael.destination;
3494 mlir::Value tempRes = dest.getMemref();
3495 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
3496 mlir::Location loc = converter.getCurrentLocation();
3497 builder.create<fir::ArrayMergeStoreOp>(loc, dest, fir::getBase(loopRes),
3498 tempRes, dest.getSlice(),
3499 dest.getTypeparams());
3501 auto arrTy = mlir::cast<fir::SequenceType>(
3502 fir::dyn_cast_ptrEleTy(tempRes.getType()));
3503 if (auto charTy = mlir::dyn_cast<fir::CharacterType>(arrTy.getEleTy())) {
3504 if (fir::characterWithDynamicLen(charTy))
3505 TODO(loc, "CHARACTER does not have constant LEN");
3506 mlir::Value len = builder.createIntegerConstant(
3507 loc, builder.getCharacterLengthType(), charTy.getLen());
3508 return fir::CharArrayBoxValue(tempRes, len, dest.getExtents());
3510 return fir::ArrayBoxValue(tempRes, dest.getExtents());
3513 static void lowerLazyArrayExpression(
3514 Fortran::lower::AbstractConverter &converter,
3515 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx,
3516 const Fortran::lower::SomeExpr &expr, mlir::Value raggedHeader) {
3517 ArrayExprLowering ael(converter, stmtCtx, symMap);
3518 ael.lowerLazyArrayExpression(expr, raggedHeader);
3521 /// Lower the expression \p expr into a buffer that is created on demand. The
3522 /// variable containing the pointer to the buffer is \p var and the variable
3523 /// containing the shape of the buffer is \p shapeBuffer.
3524 void lowerLazyArrayExpression(const Fortran::lower::SomeExpr &expr,
3525 mlir::Value header) {
3526 mlir::Location loc = getLoc();
3527 mlir::TupleType hdrTy = fir::factory::getRaggedArrayHeaderType(builder);
3528 mlir::IntegerType i32Ty = builder.getIntegerType(32);
3530 // Once the loop extents have been computed, which may require being inside
3531 // some explicit loops, lazily allocate the expression on the heap. The
3532 // following continuation creates the buffer as needed.
3533 ccPrelude = [=](llvm::ArrayRef<mlir::Value> shape) {
3534 mlir::IntegerType i64Ty = builder.getIntegerType(64);
3535 mlir::Value byteSize = builder.createIntegerConstant(loc, i64Ty, 1);
3536 fir::runtime::genRaggedArrayAllocate(
3537 loc, builder, header, /*asHeaders=*/false, byteSize, shape);
3540 // Create a dummy array_load before the loop. We're storing to a lazy
3541 // temporary, so there will be no conflict and no copy-in. TODO: skip this
3542 // as there isn't any necessity for it.
3543 ccLoadDest = [=](llvm::ArrayRef<mlir::Value> shape) -> fir::ArrayLoadOp {
3544 mlir::Value one = builder.createIntegerConstant(loc, i32Ty, 1);
3545 auto var = builder.create<fir::CoordinateOp>(
3546 loc, builder.getRefType(hdrTy.getType(1)), header, one);
3547 auto load = builder.create<fir::LoadOp>(loc, var);
3548 mlir::Type eleTy =
3549 fir::unwrapSequenceType(fir::unwrapRefType(load.getType()));
3550 auto seqTy = fir::SequenceType::get(eleTy, shape.size());
3551 mlir::Value castTo =
3552 builder.createConvert(loc, fir::HeapType::get(seqTy), load);
3553 mlir::Value shapeOp = builder.genShape(loc, shape);
3554 return builder.create<fir::ArrayLoadOp>(
3555 loc, seqTy, castTo, shapeOp, /*slice=*/mlir::Value{}, std::nullopt);
3557 // Custom lowering of the element store to deal with the extra indirection
3558 // to the lazy allocated buffer.
3559 ccStoreToDest = [=](IterSpace iters) {
3560 mlir::Value one = builder.createIntegerConstant(loc, i32Ty, 1);
3561 auto var = builder.create<fir::CoordinateOp>(
3562 loc, builder.getRefType(hdrTy.getType(1)), header, one);
3563 auto load = builder.create<fir::LoadOp>(loc, var);
3564 mlir::Type eleTy =
3565 fir::unwrapSequenceType(fir::unwrapRefType(load.getType()));
3566 auto seqTy = fir::SequenceType::get(eleTy, iters.iterVec().size());
3567 auto toTy = fir::HeapType::get(seqTy);
3568 mlir::Value castTo = builder.createConvert(loc, toTy, load);
3569 mlir::Value shape = builder.genShape(loc, genIterationShape());
3570 llvm::SmallVector<mlir::Value> indices = fir::factory::originateIndices(
3571 loc, builder, castTo.getType(), shape, iters.iterVec());
3572 auto eleAddr = builder.create<fir::ArrayCoorOp>(
3573 loc, builder.getRefType(eleTy), castTo, shape,
3574 /*slice=*/mlir::Value{}, indices, destination.getTypeparams());
3575 mlir::Value eleVal =
3576 builder.createConvert(loc, eleTy, iters.getElement());
3577 builder.create<fir::StoreOp>(loc, eleVal, eleAddr);
3578 return iters.innerArgument();
3581 // Lower the array expression now. Clean-up any temps that may have
3582 // been generated when lowering `expr` right after the lowered value
3583 // was stored to the ragged array temporary. The local temps will not
3584 // be needed afterwards.
3585 stmtCtx.pushScope();
3586 [[maybe_unused]] ExtValue loopRes = lowerArrayExpression(expr);
3587 stmtCtx.finalizeAndPop();
3588 assert(fir::getBase(loopRes));
3591 static void
3592 lowerElementalUserAssignment(Fortran::lower::AbstractConverter &converter,
3593 Fortran::lower::SymMap &symMap,
3594 Fortran::lower::StatementContext &stmtCtx,
3595 Fortran::lower::ExplicitIterSpace &explicitSpace,
3596 Fortran::lower::ImplicitIterSpace &implicitSpace,
3597 const Fortran::evaluate::ProcedureRef &procRef) {
3598 ArrayExprLowering ael(converter, stmtCtx, symMap,
3599 ConstituentSemantics::CustomCopyInCopyOut,
3600 &explicitSpace, &implicitSpace);
3601 assert(procRef.arguments().size() == 2);
3602 const auto *lhs = procRef.arguments()[0].value().UnwrapExpr();
3603 const auto *rhs = procRef.arguments()[1].value().UnwrapExpr();
3604 assert(lhs && rhs &&
3605 "user defined assignment arguments must be expressions");
3606 mlir::func::FuncOp func =
3607 Fortran::lower::CallerInterface(procRef, converter).getFuncOp();
3608 ael.lowerElementalUserAssignment(func, *lhs, *rhs);
3611 void lowerElementalUserAssignment(mlir::func::FuncOp userAssignment,
3612 const Fortran::lower::SomeExpr &lhs,
3613 const Fortran::lower::SomeExpr &rhs) {
3614 mlir::Location loc = getLoc();
3615 PushSemantics(ConstituentSemantics::CustomCopyInCopyOut);
3616 auto genArrayModify = genarr(lhs);
3617 ccStoreToDest = [=](IterSpace iters) -> ExtValue {
3618 auto modifiedArray = genArrayModify(iters);
3619 auto arrayModify = mlir::dyn_cast_or_null<fir::ArrayModifyOp>(
3620 fir::getBase(modifiedArray).getDefiningOp());
3621 assert(arrayModify && "must be created by ArrayModifyOp");
3622 fir::ExtendedValue lhs =
3623 arrayModifyToExv(builder, loc, destination, arrayModify.getResult(0));
3624 genScalarUserDefinedAssignmentCall(builder, loc, userAssignment, lhs,
3625 iters.elementExv());
3626 return modifiedArray;
3628 determineShapeOfDest(lhs);
3629 semant = ConstituentSemantics::RefTransparent;
3630 auto exv = lowerArrayExpression(rhs);
3631 if (explicitSpaceIsActive()) {
3632 explicitSpace->finalizeContext();
3633 builder.create<fir::ResultOp>(loc, fir::getBase(exv));
3634 } else {
3635 builder.create<fir::ArrayMergeStoreOp>(
3636 loc, destination, fir::getBase(exv), destination.getMemref(),
3637 destination.getSlice(), destination.getTypeparams());
3641 /// Lower an elemental subroutine call with at least one array argument.
3642 /// An elemental subroutine is an exception and does not have copy-in/copy-out
3643 /// semantics. See 15.8.3.
3644 /// Do NOT use this for user defined assignments.
3645 static void
3646 lowerElementalSubroutine(Fortran::lower::AbstractConverter &converter,
3647 Fortran::lower::SymMap &symMap,
3648 Fortran::lower::StatementContext &stmtCtx,
3649 const Fortran::lower::SomeExpr &call) {
3650 ArrayExprLowering ael(converter, stmtCtx, symMap,
3651 ConstituentSemantics::RefTransparent);
3652 ael.lowerElementalSubroutine(call);
3655 static const std::optional<Fortran::evaluate::ActualArgument>
3656 extractPassedArgFromProcRef(const Fortran::evaluate::ProcedureRef &procRef,
3657 Fortran::lower::AbstractConverter &converter) {
3658 // First look for passed object in actual arguments.
3659 for (const std::optional<Fortran::evaluate::ActualArgument> &arg :
3660 procRef.arguments())
3661 if (arg && arg->isPassedObject())
3662 return arg;
3664 // If passed object is not found by here, it means the call was fully
3665 // resolved to the correct procedure. Look for the pass object in the
3666 // dummy arguments. Pick the first polymorphic one.
3667 Fortran::lower::CallerInterface caller(procRef, converter);
3668 unsigned idx = 0;
3669 for (const auto &arg : caller.characterize().dummyArguments) {
3670 if (const auto *dummy =
3671 std::get_if<Fortran::evaluate::characteristics::DummyDataObject>(
3672 &arg.u))
3673 if (dummy->type.type().IsPolymorphic())
3674 return procRef.arguments()[idx];
3675 ++idx;
3677 return std::nullopt;
3680 // TODO: See the comment in genarr(const Fortran::lower::Parentheses<T>&).
3681 // This is skipping generation of copy-in/copy-out code for analysis that is
3682 // required when arguments are in parentheses.
3683 void lowerElementalSubroutine(const Fortran::lower::SomeExpr &call) {
3684 if (const auto *procRef =
3685 std::get_if<Fortran::evaluate::ProcedureRef>(&call.u))
3686 setLoweredProcRef(procRef);
3687 auto f = genarr(call);
3688 llvm::SmallVector<mlir::Value> shape = genIterationShape();
3689 auto [iterSpace, insPt] = genImplicitLoops(shape, /*innerArg=*/{});
3690 f(iterSpace);
3691 finalizeElementCtx();
3692 builder.restoreInsertionPoint(insPt);
3695 ExtValue lowerScalarAssignment(const Fortran::lower::SomeExpr &lhs,
3696 const Fortran::lower::SomeExpr &rhs) {
3697 PushSemantics(ConstituentSemantics::RefTransparent);
3698 // 1) Lower the rhs expression with array_fetch op(s).
3699 IterationSpace iters;
3700 iters.setElement(genarr(rhs)(iters));
3701 // 2) Lower the lhs expression to an array_update.
3702 semant = ConstituentSemantics::ProjectedCopyInCopyOut;
3703 auto lexv = genarr(lhs)(iters);
3704 // 3) Finalize the inner context.
3705 explicitSpace->finalizeContext();
3706 // 4) Thread the array value updated forward. Note: the lhs might be
3707 // ill-formed (performing scalar assignment in an array context),
3708 // in which case there is no array to thread.
3709 auto loc = getLoc();
3710 auto createResult = [&](auto op) {
3711 mlir::Value oldInnerArg = op.getSequence();
3712 std::size_t offset = explicitSpace->argPosition(oldInnerArg);
3713 explicitSpace->setInnerArg(offset, fir::getBase(lexv));
3714 finalizeElementCtx();
3715 builder.create<fir::ResultOp>(loc, fir::getBase(lexv));
3717 if (mlir::Operation *defOp = fir::getBase(lexv).getDefiningOp()) {
3718 llvm::TypeSwitch<mlir::Operation *>(defOp)
3719 .Case([&](fir::ArrayUpdateOp op) { createResult(op); })
3720 .Case([&](fir::ArrayAmendOp op) { createResult(op); })
3721 .Case([&](fir::ArrayModifyOp op) { createResult(op); })
3722 .Default([&](mlir::Operation *) { finalizeElementCtx(); });
3723 } else {
3724 // `lhs` isn't from a `fir.array_load`, so there is no array modifications
3725 // to thread through the iteration space.
3726 finalizeElementCtx();
3728 return lexv;
3731 static ExtValue lowerScalarUserAssignment(
3732 Fortran::lower::AbstractConverter &converter,
3733 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx,
3734 Fortran::lower::ExplicitIterSpace &explicitIterSpace,
3735 mlir::func::FuncOp userAssignmentFunction,
3736 const Fortran::lower::SomeExpr &lhs,
3737 const Fortran::lower::SomeExpr &rhs) {
3738 Fortran::lower::ImplicitIterSpace implicit;
3739 ArrayExprLowering ael(converter, stmtCtx, symMap,
3740 ConstituentSemantics::RefTransparent,
3741 &explicitIterSpace, &implicit);
3742 return ael.lowerScalarUserAssignment(userAssignmentFunction, lhs, rhs);
3745 ExtValue lowerScalarUserAssignment(mlir::func::FuncOp userAssignment,
3746 const Fortran::lower::SomeExpr &lhs,
3747 const Fortran::lower::SomeExpr &rhs) {
3748 mlir::Location loc = getLoc();
3749 if (rhs.Rank() > 0)
3750 TODO(loc, "user-defined elemental assigment from expression with rank");
3751 // 1) Lower the rhs expression with array_fetch op(s).
3752 IterationSpace iters;
3753 iters.setElement(genarr(rhs)(iters));
3754 fir::ExtendedValue elementalExv = iters.elementExv();
3755 // 2) Lower the lhs expression to an array_modify.
3756 semant = ConstituentSemantics::CustomCopyInCopyOut;
3757 auto lexv = genarr(lhs)(iters);
3758 bool isIllFormedLHS = false;
3759 // 3) Insert the call
3760 if (auto modifyOp = mlir::dyn_cast<fir::ArrayModifyOp>(
3761 fir::getBase(lexv).getDefiningOp())) {
3762 mlir::Value oldInnerArg = modifyOp.getSequence();
3763 std::size_t offset = explicitSpace->argPosition(oldInnerArg);
3764 explicitSpace->setInnerArg(offset, fir::getBase(lexv));
3765 auto lhsLoad = explicitSpace->getLhsLoad(0);
3766 assert(lhsLoad.has_value());
3767 fir::ExtendedValue exv =
3768 arrayModifyToExv(builder, loc, *lhsLoad, modifyOp.getResult(0));
3769 genScalarUserDefinedAssignmentCall(builder, loc, userAssignment, exv,
3770 elementalExv);
3771 } else {
3772 // LHS is ill formed, it is a scalar with no references to FORALL
3773 // subscripts, so there is actually no array assignment here. The user
3774 // code is probably bad, but still insert user assignment call since it
3775 // was not rejected by semantics (a warning was emitted).
3776 isIllFormedLHS = true;
3777 genScalarUserDefinedAssignmentCall(builder, getLoc(), userAssignment,
3778 lexv, elementalExv);
3780 // 4) Finalize the inner context.
3781 explicitSpace->finalizeContext();
3782 // 5). Thread the array value updated forward.
3783 if (!isIllFormedLHS) {
3784 finalizeElementCtx();
3785 builder.create<fir::ResultOp>(getLoc(), fir::getBase(lexv));
3787 return lexv;
3790 private:
3791 void determineShapeOfDest(const fir::ExtendedValue &lhs) {
3792 destShape = fir::factory::getExtents(getLoc(), builder, lhs);
3795 void determineShapeOfDest(const Fortran::lower::SomeExpr &lhs) {
3796 if (!destShape.empty())
3797 return;
3798 if (explicitSpaceIsActive() && determineShapeWithSlice(lhs))
3799 return;
3800 mlir::Type idxTy = builder.getIndexType();
3801 mlir::Location loc = getLoc();
3802 if (std::optional<Fortran::evaluate::ConstantSubscripts> constantShape =
3803 Fortran::evaluate::GetConstantExtents(converter.getFoldingContext(),
3804 lhs))
3805 for (Fortran::common::ConstantSubscript extent : *constantShape)
3806 destShape.push_back(builder.createIntegerConstant(loc, idxTy, extent));
3809 bool genShapeFromDataRef(const Fortran::semantics::Symbol &x) {
3810 return false;
3812 bool genShapeFromDataRef(const Fortran::evaluate::CoarrayRef &) {
3813 TODO(getLoc(), "coarray: reference to a coarray in an expression");
3814 return false;
3816 bool genShapeFromDataRef(const Fortran::evaluate::Component &x) {
3817 return x.base().Rank() > 0 ? genShapeFromDataRef(x.base()) : false;
3819 bool genShapeFromDataRef(const Fortran::evaluate::ArrayRef &x) {
3820 if (x.Rank() == 0)
3821 return false;
3822 if (x.base().Rank() > 0)
3823 if (genShapeFromDataRef(x.base()))
3824 return true;
3825 // x has rank and x.base did not produce a shape.
3826 ExtValue exv = x.base().IsSymbol() ? asScalarRef(getFirstSym(x.base()))
3827 : asScalarRef(x.base().GetComponent());
3828 mlir::Location loc = getLoc();
3829 mlir::IndexType idxTy = builder.getIndexType();
3830 llvm::SmallVector<mlir::Value> definedShape =
3831 fir::factory::getExtents(loc, builder, exv);
3832 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
3833 for (auto ss : llvm::enumerate(x.subscript())) {
3834 Fortran::common::visit(
3835 Fortran::common::visitors{
3836 [&](const Fortran::evaluate::Triplet &trip) {
3837 // For a subscript of triple notation, we compute the
3838 // range of this dimension of the iteration space.
3839 auto lo = [&]() {
3840 if (auto optLo = trip.lower())
3841 return fir::getBase(asScalar(*optLo));
3842 return getLBound(exv, ss.index(), one);
3843 }();
3844 auto hi = [&]() {
3845 if (auto optHi = trip.upper())
3846 return fir::getBase(asScalar(*optHi));
3847 return getUBound(exv, ss.index(), one);
3848 }();
3849 auto step = builder.createConvert(
3850 loc, idxTy, fir::getBase(asScalar(trip.stride())));
3851 auto extent =
3852 builder.genExtentFromTriplet(loc, lo, hi, step, idxTy);
3853 destShape.push_back(extent);
3855 [&](auto) {}},
3856 ss.value().u);
3858 return true;
3860 bool genShapeFromDataRef(const Fortran::evaluate::NamedEntity &x) {
3861 if (x.IsSymbol())
3862 return genShapeFromDataRef(getFirstSym(x));
3863 return genShapeFromDataRef(x.GetComponent());
3865 bool genShapeFromDataRef(const Fortran::evaluate::DataRef &x) {
3866 return Fortran::common::visit(
3867 [&](const auto &v) { return genShapeFromDataRef(v); }, x.u);
3870 /// When in an explicit space, the ranked component must be evaluated to
3871 /// determine the actual number of iterations when slicing triples are
3872 /// present. Lower these expressions here.
3873 bool determineShapeWithSlice(const Fortran::lower::SomeExpr &lhs) {
3874 LLVM_DEBUG(Fortran::lower::DumpEvaluateExpr::dump(
3875 llvm::dbgs() << "determine shape of:\n", lhs));
3876 // FIXME: We may not want to use ExtractDataRef here since it doesn't deal
3877 // with substrings, etc.
3878 std::optional<Fortran::evaluate::DataRef> dref =
3879 Fortran::evaluate::ExtractDataRef(lhs);
3880 return dref.has_value() ? genShapeFromDataRef(*dref) : false;
3883 /// CHARACTER and derived type elements are treated as memory references. The
3884 /// numeric types are treated as values.
3885 static mlir::Type adjustedArraySubtype(mlir::Type ty,
3886 mlir::ValueRange indices) {
3887 mlir::Type pathTy = fir::applyPathToType(ty, indices);
3888 assert(pathTy && "indices failed to apply to type");
3889 return adjustedArrayElementType(pathTy);
3892 /// Lower rhs of an array expression.
3893 ExtValue lowerArrayExpression(const Fortran::lower::SomeExpr &exp) {
3894 mlir::Type resTy = converter.genType(exp);
3896 if (fir::isPolymorphicType(resTy) &&
3897 Fortran::evaluate::HasVectorSubscript(exp))
3898 TODO(getLoc(),
3899 "polymorphic array expression lowering with vector subscript");
3901 return Fortran::common::visit(
3902 [&](const auto &e) { return lowerArrayExpression(genarr(e), resTy); },
3903 exp.u);
3905 ExtValue lowerArrayExpression(const ExtValue &exv) {
3906 assert(!explicitSpace);
3907 mlir::Type resTy = fir::unwrapPassByRefType(fir::getBase(exv).getType());
3908 return lowerArrayExpression(genarr(exv), resTy);
3911 void populateBounds(llvm::SmallVectorImpl<mlir::Value> &bounds,
3912 const Fortran::evaluate::Substring *substring) {
3913 if (!substring)
3914 return;
3915 bounds.push_back(fir::getBase(asScalar(substring->lower())));
3916 if (auto upper = substring->upper())
3917 bounds.push_back(fir::getBase(asScalar(*upper)));
3920 /// Convert the original value, \p origVal, to type \p eleTy. When in a
3921 /// pointer assignment context, generate an appropriate `fir.rebox` for
3922 /// dealing with any bounds parameters on the pointer assignment.
3923 mlir::Value convertElementForUpdate(mlir::Location loc, mlir::Type eleTy,
3924 mlir::Value origVal) {
3925 if (auto origEleTy = fir::dyn_cast_ptrEleTy(origVal.getType()))
3926 if (mlir::isa<fir::BaseBoxType>(origEleTy)) {
3927 // If origVal is a box variable, load it so it is in the value domain.
3928 origVal = builder.create<fir::LoadOp>(loc, origVal);
3930 if (mlir::isa<fir::BoxType>(origVal.getType()) &&
3931 !mlir::isa<fir::BoxType>(eleTy)) {
3932 if (isPointerAssignment())
3933 TODO(loc, "lhs of pointer assignment returned unexpected value");
3934 TODO(loc, "invalid box conversion in elemental computation");
3936 if (isPointerAssignment() && mlir::isa<fir::BoxType>(eleTy) &&
3937 !mlir::isa<fir::BoxType>(origVal.getType())) {
3938 // This is a pointer assignment and the rhs is a raw reference to a TARGET
3939 // in memory. Embox the reference so it can be stored to the boxed
3940 // POINTER variable.
3941 assert(fir::isa_ref_type(origVal.getType()));
3942 if (auto eleTy = fir::dyn_cast_ptrEleTy(origVal.getType());
3943 fir::hasDynamicSize(eleTy))
3944 TODO(loc, "TARGET of pointer assignment with runtime size/shape");
3945 auto memrefTy = fir::boxMemRefType(mlir::cast<fir::BoxType>(eleTy));
3946 auto castTo = builder.createConvert(loc, memrefTy, origVal);
3947 origVal = builder.create<fir::EmboxOp>(loc, eleTy, castTo);
3949 mlir::Value val = builder.convertWithSemantics(loc, eleTy, origVal);
3950 if (isBoundsSpec()) {
3951 assert(lbounds.has_value());
3952 auto lbs = *lbounds;
3953 if (lbs.size() > 0) {
3954 // Rebox the value with user-specified shift.
3955 auto shiftTy = fir::ShiftType::get(eleTy.getContext(), lbs.size());
3956 mlir::Value shiftOp = builder.create<fir::ShiftOp>(loc, shiftTy, lbs);
3957 val = builder.create<fir::ReboxOp>(loc, eleTy, val, shiftOp,
3958 mlir::Value{});
3960 } else if (isBoundsRemap()) {
3961 assert(lbounds.has_value());
3962 auto lbs = *lbounds;
3963 if (lbs.size() > 0) {
3964 // Rebox the value with user-specified shift and shape.
3965 assert(ubounds.has_value());
3966 auto shapeShiftArgs = flatZip(lbs, *ubounds);
3967 auto shapeTy = fir::ShapeShiftType::get(eleTy.getContext(), lbs.size());
3968 mlir::Value shapeShift =
3969 builder.create<fir::ShapeShiftOp>(loc, shapeTy, shapeShiftArgs);
3970 val = builder.create<fir::ReboxOp>(loc, eleTy, val, shapeShift,
3971 mlir::Value{});
3974 return val;
3977 /// Default store to destination implementation.
3978 /// This implements the default case, which is to assign the value in
3979 /// `iters.element` into the destination array, `iters.innerArgument`. Handles
3980 /// by value and by reference assignment.
3981 CC defaultStoreToDestination(const Fortran::evaluate::Substring *substring) {
3982 return [=](IterSpace iterSpace) -> ExtValue {
3983 mlir::Location loc = getLoc();
3984 mlir::Value innerArg = iterSpace.innerArgument();
3985 fir::ExtendedValue exv = iterSpace.elementExv();
3986 mlir::Type arrTy = innerArg.getType();
3987 mlir::Type eleTy = fir::applyPathToType(arrTy, iterSpace.iterVec());
3988 if (isAdjustedArrayElementType(eleTy)) {
3989 // The elemental update is in the memref domain. Under this semantics,
3990 // we must always copy the computed new element from its location in
3991 // memory into the destination array.
3992 mlir::Type resRefTy = builder.getRefType(eleTy);
3993 // Get a reference to the array element to be amended.
3994 auto arrayOp = builder.create<fir::ArrayAccessOp>(
3995 loc, resRefTy, innerArg, iterSpace.iterVec(),
3996 fir::factory::getTypeParams(loc, builder, destination));
3997 if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
3998 llvm::SmallVector<mlir::Value> substringBounds;
3999 populateBounds(substringBounds, substring);
4000 mlir::Value dstLen = fir::factory::genLenOfCharacter(
4001 builder, loc, destination, iterSpace.iterVec(), substringBounds);
4002 fir::ArrayAmendOp amend = createCharArrayAmend(
4003 loc, builder, arrayOp, dstLen, exv, innerArg, substringBounds);
4004 return abstractArrayExtValue(amend, dstLen);
4006 if (fir::isa_derived(eleTy)) {
4007 fir::ArrayAmendOp amend = createDerivedArrayAmend(
4008 loc, destination, builder, arrayOp, exv, eleTy, innerArg);
4009 return abstractArrayExtValue(amend /*FIXME: typeparams?*/);
4011 assert(mlir::isa<fir::SequenceType>(eleTy) && "must be an array");
4012 TODO(loc, "array (as element) assignment");
4014 // By value semantics. The element is being assigned by value.
4015 auto ele = convertElementForUpdate(loc, eleTy, fir::getBase(exv));
4016 auto update = builder.create<fir::ArrayUpdateOp>(
4017 loc, arrTy, innerArg, ele, iterSpace.iterVec(),
4018 destination.getTypeparams());
4019 return abstractArrayExtValue(update);
4023 /// For an elemental array expression.
4024 /// 1. Lower the scalars and array loads.
4025 /// 2. Create the iteration space.
4026 /// 3. Create the element-by-element computation in the loop.
4027 /// 4. Return the resulting array value.
4028 /// If no destination was set in the array context, a temporary of
4029 /// \p resultTy will be created to hold the evaluated expression.
4030 /// Otherwise, \p resultTy is ignored and the expression is evaluated
4031 /// in the destination. \p f is a continuation built from an
4032 /// evaluate::Expr or an ExtendedValue.
4033 ExtValue lowerArrayExpression(CC f, mlir::Type resultTy) {
4034 mlir::Location loc = getLoc();
4035 auto [iterSpace, insPt] = genIterSpace(resultTy);
4036 auto exv = f(iterSpace);
4037 iterSpace.setElement(std::move(exv));
4038 auto lambda = ccStoreToDest
4039 ? *ccStoreToDest
4040 : defaultStoreToDestination(/*substring=*/nullptr);
4041 mlir::Value updVal = fir::getBase(lambda(iterSpace));
4042 finalizeElementCtx();
4043 builder.create<fir::ResultOp>(loc, updVal);
4044 builder.restoreInsertionPoint(insPt);
4045 return abstractArrayExtValue(iterSpace.outerResult());
4048 /// Compute the shape of a slice.
4049 llvm::SmallVector<mlir::Value> computeSliceShape(mlir::Value slice) {
4050 llvm::SmallVector<mlir::Value> slicedShape;
4051 auto slOp = mlir::cast<fir::SliceOp>(slice.getDefiningOp());
4052 mlir::Operation::operand_range triples = slOp.getTriples();
4053 mlir::IndexType idxTy = builder.getIndexType();
4054 mlir::Location loc = getLoc();
4055 for (unsigned i = 0, end = triples.size(); i < end; i += 3) {
4056 if (!mlir::isa_and_nonnull<fir::UndefOp>(
4057 triples[i + 1].getDefiningOp())) {
4058 // (..., lb:ub:step, ...) case: extent = max((ub-lb+step)/step, 0)
4059 // See Fortran 2018 9.5.3.3.2 section for more details.
4060 mlir::Value res = builder.genExtentFromTriplet(
4061 loc, triples[i], triples[i + 1], triples[i + 2], idxTy);
4062 slicedShape.emplace_back(res);
4063 } else {
4064 // do nothing. `..., i, ...` case, so dimension is dropped.
4067 return slicedShape;
4070 /// Get the shape from an ArrayOperand. The shape of the array is adjusted if
4071 /// the array was sliced.
4072 llvm::SmallVector<mlir::Value> getShape(ArrayOperand array) {
4073 if (array.slice)
4074 return computeSliceShape(array.slice);
4075 if (mlir::isa<fir::BaseBoxType>(array.memref.getType()))
4076 return fir::factory::readExtents(builder, getLoc(),
4077 fir::BoxValue{array.memref});
4078 return fir::factory::getExtents(array.shape);
4081 /// Get the shape from an ArrayLoad.
4082 llvm::SmallVector<mlir::Value> getShape(fir::ArrayLoadOp arrayLoad) {
4083 return getShape(ArrayOperand{arrayLoad.getMemref(), arrayLoad.getShape(),
4084 arrayLoad.getSlice()});
4087 /// Returns the first array operand that may not be absent. If all
4088 /// array operands may be absent, return the first one.
4089 const ArrayOperand &getInducingShapeArrayOperand() const {
4090 assert(!arrayOperands.empty());
4091 for (const ArrayOperand &op : arrayOperands)
4092 if (!op.mayBeAbsent)
4093 return op;
4094 // If all arrays operand appears in optional position, then none of them
4095 // is allowed to be absent as per 15.5.2.12 point 3. (6). Just pick the
4096 // first operands.
4097 // TODO: There is an opportunity to add a runtime check here that
4098 // this array is present as required.
4099 return arrayOperands[0];
4102 /// Generate the shape of the iteration space over the array expression. The
4103 /// iteration space may be implicit, explicit, or both. If it is implied it is
4104 /// based on the destination and operand array loads, or an optional
4105 /// Fortran::evaluate::Shape from the front end. If the shape is explicit,
4106 /// this returns any implicit shape component, if it exists.
4107 llvm::SmallVector<mlir::Value> genIterationShape() {
4108 // Use the precomputed destination shape.
4109 if (!destShape.empty())
4110 return destShape;
4111 // Otherwise, use the destination's shape.
4112 if (destination)
4113 return getShape(destination);
4114 // Otherwise, use the first ArrayLoad operand shape.
4115 if (!arrayOperands.empty())
4116 return getShape(getInducingShapeArrayOperand());
4117 // Otherwise, in elemental context, try to find the passed object and
4118 // retrieve the iteration shape from it.
4119 if (loweredProcRef && loweredProcRef->IsElemental()) {
4120 const std::optional<Fortran::evaluate::ActualArgument> passArg =
4121 extractPassedArgFromProcRef(*loweredProcRef, converter);
4122 if (passArg) {
4123 ExtValue exv = asScalarRef(*passArg->UnwrapExpr());
4124 fir::FirOpBuilder *builder = &converter.getFirOpBuilder();
4125 auto extents = fir::factory::getExtents(getLoc(), *builder, exv);
4126 if (extents.size() == 0)
4127 TODO(getLoc(), "getting shape from polymorphic array in elemental "
4128 "procedure reference");
4129 return extents;
4132 fir::emitFatalError(getLoc(),
4133 "failed to compute the array expression shape");
4136 bool explicitSpaceIsActive() const {
4137 return explicitSpace && explicitSpace->isActive();
4140 bool implicitSpaceHasMasks() const {
4141 return implicitSpace && !implicitSpace->empty();
4144 CC genMaskAccess(mlir::Value tmp, mlir::Value shape) {
4145 mlir::Location loc = getLoc();
4146 return [=, builder = &converter.getFirOpBuilder()](IterSpace iters) {
4147 mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(tmp.getType());
4148 auto eleTy = mlir::cast<fir::SequenceType>(arrTy).getEleTy();
4149 mlir::Type eleRefTy = builder->getRefType(eleTy);
4150 mlir::IntegerType i1Ty = builder->getI1Type();
4151 // Adjust indices for any shift of the origin of the array.
4152 llvm::SmallVector<mlir::Value> indices = fir::factory::originateIndices(
4153 loc, *builder, tmp.getType(), shape, iters.iterVec());
4154 auto addr =
4155 builder->create<fir::ArrayCoorOp>(loc, eleRefTy, tmp, shape,
4156 /*slice=*/mlir::Value{}, indices,
4157 /*typeParams=*/std::nullopt);
4158 auto load = builder->create<fir::LoadOp>(loc, addr);
4159 return builder->createConvert(loc, i1Ty, load);
4163 /// Construct the incremental instantiations of the ragged array structure.
4164 /// Rebind the lazy buffer variable, etc. as we go.
4165 template <bool withAllocation = false>
4166 mlir::Value prepareRaggedArrays(Fortran::lower::FrontEndExpr expr) {
4167 assert(explicitSpaceIsActive());
4168 mlir::Location loc = getLoc();
4169 mlir::TupleType raggedTy = fir::factory::getRaggedArrayHeaderType(builder);
4170 llvm::SmallVector<llvm::SmallVector<fir::DoLoopOp>> loopStack =
4171 explicitSpace->getLoopStack();
4172 const std::size_t depth = loopStack.size();
4173 mlir::IntegerType i64Ty = builder.getIntegerType(64);
4174 [[maybe_unused]] mlir::Value byteSize =
4175 builder.createIntegerConstant(loc, i64Ty, 1);
4176 mlir::Value header = implicitSpace->lookupMaskHeader(expr);
4177 for (std::remove_const_t<decltype(depth)> i = 0; i < depth; ++i) {
4178 auto insPt = builder.saveInsertionPoint();
4179 if (i < depth - 1)
4180 builder.setInsertionPoint(loopStack[i + 1][0]);
4182 // Compute and gather the extents.
4183 llvm::SmallVector<mlir::Value> extents;
4184 for (auto doLoop : loopStack[i])
4185 extents.push_back(builder.genExtentFromTriplet(
4186 loc, doLoop.getLowerBound(), doLoop.getUpperBound(),
4187 doLoop.getStep(), i64Ty));
4188 if constexpr (withAllocation) {
4189 fir::runtime::genRaggedArrayAllocate(
4190 loc, builder, header, /*asHeader=*/true, byteSize, extents);
4193 // Compute the dynamic position into the header.
4194 llvm::SmallVector<mlir::Value> offsets;
4195 for (auto doLoop : loopStack[i]) {
4196 auto m = builder.create<mlir::arith::SubIOp>(
4197 loc, doLoop.getInductionVar(), doLoop.getLowerBound());
4198 auto n = builder.create<mlir::arith::DivSIOp>(loc, m, doLoop.getStep());
4199 mlir::Value one = builder.createIntegerConstant(loc, n.getType(), 1);
4200 offsets.push_back(builder.create<mlir::arith::AddIOp>(loc, n, one));
4202 mlir::IntegerType i32Ty = builder.getIntegerType(32);
4203 mlir::Value uno = builder.createIntegerConstant(loc, i32Ty, 1);
4204 mlir::Type coorTy = builder.getRefType(raggedTy.getType(1));
4205 auto hdOff = builder.create<fir::CoordinateOp>(loc, coorTy, header, uno);
4206 auto toTy = fir::SequenceType::get(raggedTy, offsets.size());
4207 mlir::Type toRefTy = builder.getRefType(toTy);
4208 auto ldHdr = builder.create<fir::LoadOp>(loc, hdOff);
4209 mlir::Value hdArr = builder.createConvert(loc, toRefTy, ldHdr);
4210 auto shapeOp = builder.genShape(loc, extents);
4211 header = builder.create<fir::ArrayCoorOp>(
4212 loc, builder.getRefType(raggedTy), hdArr, shapeOp,
4213 /*slice=*/mlir::Value{}, offsets,
4214 /*typeparams=*/mlir::ValueRange{});
4215 auto hdrVar = builder.create<fir::CoordinateOp>(loc, coorTy, header, uno);
4216 auto inVar = builder.create<fir::LoadOp>(loc, hdrVar);
4217 mlir::Value two = builder.createIntegerConstant(loc, i32Ty, 2);
4218 mlir::Type coorTy2 = builder.getRefType(raggedTy.getType(2));
4219 auto hdrSh = builder.create<fir::CoordinateOp>(loc, coorTy2, header, two);
4220 auto shapePtr = builder.create<fir::LoadOp>(loc, hdrSh);
4221 // Replace the binding.
4222 implicitSpace->rebind(expr, genMaskAccess(inVar, shapePtr));
4223 if (i < depth - 1)
4224 builder.restoreInsertionPoint(insPt);
4226 return header;
4229 /// Lower mask expressions with implied iteration spaces from the variants of
4230 /// WHERE syntax. Since it is legal for mask expressions to have side-effects
4231 /// and modify values that will be used for the lhs, rhs, or both of
4232 /// subsequent assignments, the mask must be evaluated before the assignment
4233 /// is processed.
4234 /// Mask expressions are array expressions too.
4235 void genMasks() {
4236 // Lower the mask expressions, if any.
4237 if (implicitSpaceHasMasks()) {
4238 mlir::Location loc = getLoc();
4239 // Mask expressions are array expressions too.
4240 for (const auto *e : implicitSpace->getExprs())
4241 if (e && !implicitSpace->isLowered(e)) {
4242 if (mlir::Value var = implicitSpace->lookupMaskVariable(e)) {
4243 // Allocate the mask buffer lazily.
4244 assert(explicitSpaceIsActive());
4245 mlir::Value header =
4246 prepareRaggedArrays</*withAllocations=*/true>(e);
4247 Fortran::lower::createLazyArrayTempValue(converter, *e, header,
4248 symMap, stmtCtx);
4249 // Close the explicit loops.
4250 builder.create<fir::ResultOp>(loc, explicitSpace->getInnerArgs());
4251 builder.setInsertionPointAfter(explicitSpace->getOuterLoop());
4252 // Open a new copy of the explicit loop nest.
4253 explicitSpace->genLoopNest();
4254 continue;
4256 fir::ExtendedValue tmp = Fortran::lower::createSomeArrayTempValue(
4257 converter, *e, symMap, stmtCtx);
4258 mlir::Value shape = builder.createShape(loc, tmp);
4259 implicitSpace->bind(e, genMaskAccess(fir::getBase(tmp), shape));
4262 // Set buffer from the header.
4263 for (const auto *e : implicitSpace->getExprs()) {
4264 if (!e)
4265 continue;
4266 if (implicitSpace->lookupMaskVariable(e)) {
4267 // Index into the ragged buffer to retrieve cached results.
4268 const int rank = e->Rank();
4269 assert(destShape.empty() ||
4270 static_cast<std::size_t>(rank) == destShape.size());
4271 mlir::Value header = prepareRaggedArrays(e);
4272 mlir::TupleType raggedTy =
4273 fir::factory::getRaggedArrayHeaderType(builder);
4274 mlir::IntegerType i32Ty = builder.getIntegerType(32);
4275 mlir::Value one = builder.createIntegerConstant(loc, i32Ty, 1);
4276 auto coor1 = builder.create<fir::CoordinateOp>(
4277 loc, builder.getRefType(raggedTy.getType(1)), header, one);
4278 auto db = builder.create<fir::LoadOp>(loc, coor1);
4279 mlir::Type eleTy =
4280 fir::unwrapSequenceType(fir::unwrapRefType(db.getType()));
4281 mlir::Type buffTy =
4282 builder.getRefType(fir::SequenceType::get(eleTy, rank));
4283 // Address of ragged buffer data.
4284 mlir::Value buff = builder.createConvert(loc, buffTy, db);
4286 mlir::Value two = builder.createIntegerConstant(loc, i32Ty, 2);
4287 auto coor2 = builder.create<fir::CoordinateOp>(
4288 loc, builder.getRefType(raggedTy.getType(2)), header, two);
4289 auto shBuff = builder.create<fir::LoadOp>(loc, coor2);
4290 mlir::IntegerType i64Ty = builder.getIntegerType(64);
4291 mlir::IndexType idxTy = builder.getIndexType();
4292 llvm::SmallVector<mlir::Value> extents;
4293 for (std::remove_const_t<decltype(rank)> i = 0; i < rank; ++i) {
4294 mlir::Value off = builder.createIntegerConstant(loc, i32Ty, i);
4295 auto coor = builder.create<fir::CoordinateOp>(
4296 loc, builder.getRefType(i64Ty), shBuff, off);
4297 auto ldExt = builder.create<fir::LoadOp>(loc, coor);
4298 extents.push_back(builder.createConvert(loc, idxTy, ldExt));
4300 if (destShape.empty())
4301 destShape = extents;
4302 // Construct shape of buffer.
4303 mlir::Value shapeOp = builder.genShape(loc, extents);
4305 // Replace binding with the local result.
4306 implicitSpace->rebind(e, genMaskAccess(buff, shapeOp));
4312 // FIXME: should take multiple inner arguments.
4313 std::pair<IterationSpace, mlir::OpBuilder::InsertPoint>
4314 genImplicitLoops(mlir::ValueRange shape, mlir::Value innerArg) {
4315 mlir::Location loc = getLoc();
4316 mlir::IndexType idxTy = builder.getIndexType();
4317 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
4318 mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0);
4319 llvm::SmallVector<mlir::Value> loopUppers;
4321 // Convert any implied shape to closed interval form. The fir.do_loop will
4322 // run from 0 to `extent - 1` inclusive.
4323 for (auto extent : shape)
4324 loopUppers.push_back(
4325 builder.create<mlir::arith::SubIOp>(loc, extent, one));
4327 // Iteration space is created with outermost columns, innermost rows
4328 llvm::SmallVector<fir::DoLoopOp> loops;
4330 const std::size_t loopDepth = loopUppers.size();
4331 llvm::SmallVector<mlir::Value> ivars;
4333 for (auto i : llvm::enumerate(llvm::reverse(loopUppers))) {
4334 if (i.index() > 0) {
4335 assert(!loops.empty());
4336 builder.setInsertionPointToStart(loops.back().getBody());
4338 fir::DoLoopOp loop;
4339 if (innerArg) {
4340 loop = builder.create<fir::DoLoopOp>(
4341 loc, zero, i.value(), one, isUnordered(),
4342 /*finalCount=*/false, mlir::ValueRange{innerArg});
4343 innerArg = loop.getRegionIterArgs().front();
4344 if (explicitSpaceIsActive())
4345 explicitSpace->setInnerArg(0, innerArg);
4346 } else {
4347 loop = builder.create<fir::DoLoopOp>(loc, zero, i.value(), one,
4348 isUnordered(),
4349 /*finalCount=*/false);
4351 ivars.push_back(loop.getInductionVar());
4352 loops.push_back(loop);
4355 if (innerArg)
4356 for (std::remove_const_t<decltype(loopDepth)> i = 0; i + 1 < loopDepth;
4357 ++i) {
4358 builder.setInsertionPointToEnd(loops[i].getBody());
4359 builder.create<fir::ResultOp>(loc, loops[i + 1].getResult(0));
4362 // Move insertion point to the start of the innermost loop in the nest.
4363 builder.setInsertionPointToStart(loops.back().getBody());
4364 // Set `afterLoopNest` to just after the entire loop nest.
4365 auto currPt = builder.saveInsertionPoint();
4366 builder.setInsertionPointAfter(loops[0]);
4367 auto afterLoopNest = builder.saveInsertionPoint();
4368 builder.restoreInsertionPoint(currPt);
4370 // Put the implicit loop variables in row to column order to match FIR's
4371 // Ops. (The loops were constructed from outermost column to innermost
4372 // row.)
4373 mlir::Value outerRes;
4374 if (loops[0].getNumResults() != 0)
4375 outerRes = loops[0].getResult(0);
4376 return {IterationSpace(innerArg, outerRes, llvm::reverse(ivars)),
4377 afterLoopNest};
4380 /// Build the iteration space into which the array expression will be lowered.
4381 /// The resultType is used to create a temporary, if needed.
4382 std::pair<IterationSpace, mlir::OpBuilder::InsertPoint>
4383 genIterSpace(mlir::Type resultType) {
4384 mlir::Location loc = getLoc();
4385 llvm::SmallVector<mlir::Value> shape = genIterationShape();
4386 if (!destination) {
4387 // Allocate storage for the result if it is not already provided.
4388 destination = createAndLoadSomeArrayTemp(resultType, shape);
4391 // Generate the lazy mask allocation, if one was given.
4392 if (ccPrelude)
4393 (*ccPrelude)(shape);
4395 // Now handle the implicit loops.
4396 mlir::Value inner = explicitSpaceIsActive()
4397 ? explicitSpace->getInnerArgs().front()
4398 : destination.getResult();
4399 auto [iters, afterLoopNest] = genImplicitLoops(shape, inner);
4400 mlir::Value innerArg = iters.innerArgument();
4402 // Generate the mask conditional structure, if there are masks. Unlike the
4403 // explicit masks, which are interleaved, these mask expression appear in
4404 // the innermost loop.
4405 if (implicitSpaceHasMasks()) {
4406 // Recover the cached condition from the mask buffer.
4407 auto genCond = [&](Fortran::lower::FrontEndExpr e, IterSpace iters) {
4408 return implicitSpace->getBoundClosure(e)(iters);
4411 // Handle the negated conditions in topological order of the WHERE
4412 // clauses. See 10.2.3.2p4 as to why this control structure is produced.
4413 for (llvm::SmallVector<Fortran::lower::FrontEndExpr> maskExprs :
4414 implicitSpace->getMasks()) {
4415 const std::size_t size = maskExprs.size() - 1;
4416 auto genFalseBlock = [&](const auto *e, auto &&cond) {
4417 auto ifOp = builder.create<fir::IfOp>(
4418 loc, mlir::TypeRange{innerArg.getType()}, fir::getBase(cond),
4419 /*withElseRegion=*/true);
4420 builder.create<fir::ResultOp>(loc, ifOp.getResult(0));
4421 builder.setInsertionPointToStart(&ifOp.getThenRegion().front());
4422 builder.create<fir::ResultOp>(loc, innerArg);
4423 builder.setInsertionPointToStart(&ifOp.getElseRegion().front());
4425 auto genTrueBlock = [&](const auto *e, auto &&cond) {
4426 auto ifOp = builder.create<fir::IfOp>(
4427 loc, mlir::TypeRange{innerArg.getType()}, fir::getBase(cond),
4428 /*withElseRegion=*/true);
4429 builder.create<fir::ResultOp>(loc, ifOp.getResult(0));
4430 builder.setInsertionPointToStart(&ifOp.getElseRegion().front());
4431 builder.create<fir::ResultOp>(loc, innerArg);
4432 builder.setInsertionPointToStart(&ifOp.getThenRegion().front());
4434 for (std::remove_const_t<decltype(size)> i = 0; i < size; ++i)
4435 if (const auto *e = maskExprs[i])
4436 genFalseBlock(e, genCond(e, iters));
4438 // The last condition is either non-negated or unconditionally negated.
4439 if (const auto *e = maskExprs[size])
4440 genTrueBlock(e, genCond(e, iters));
4444 // We're ready to lower the body (an assignment statement) for this context
4445 // of loop nests at this point.
4446 return {iters, afterLoopNest};
4449 fir::ArrayLoadOp
4450 createAndLoadSomeArrayTemp(mlir::Type type,
4451 llvm::ArrayRef<mlir::Value> shape) {
4452 mlir::Location loc = getLoc();
4453 if (fir::isPolymorphicType(type))
4454 TODO(loc, "polymorphic array temporary");
4455 if (ccLoadDest)
4456 return (*ccLoadDest)(shape);
4457 auto seqTy = mlir::dyn_cast<fir::SequenceType>(type);
4458 assert(seqTy && "must be an array");
4459 // TODO: Need to thread the LEN parameters here. For character, they may
4460 // differ from the operands length (e.g concatenation). So the array loads
4461 // type parameters are not enough.
4462 if (auto charTy = mlir::dyn_cast<fir::CharacterType>(seqTy.getEleTy()))
4463 if (charTy.hasDynamicLen())
4464 TODO(loc, "character array expression temp with dynamic length");
4465 if (auto recTy = mlir::dyn_cast<fir::RecordType>(seqTy.getEleTy()))
4466 if (recTy.getNumLenParams() > 0)
4467 TODO(loc, "derived type array expression temp with LEN parameters");
4468 if (mlir::Type eleTy = fir::unwrapSequenceType(type);
4469 fir::isRecordWithAllocatableMember(eleTy))
4470 TODO(loc, "creating an array temp where the element type has "
4471 "allocatable members");
4472 mlir::Value temp = !seqTy.hasDynamicExtents()
4473 ? builder.create<fir::AllocMemOp>(loc, type)
4474 : builder.create<fir::AllocMemOp>(
4475 loc, type, ".array.expr", std::nullopt, shape);
4476 fir::FirOpBuilder *bldr = &converter.getFirOpBuilder();
4477 stmtCtx.attachCleanup(
4478 [bldr, loc, temp]() { bldr->create<fir::FreeMemOp>(loc, temp); });
4479 mlir::Value shapeOp = genShapeOp(shape);
4480 return builder.create<fir::ArrayLoadOp>(loc, seqTy, temp, shapeOp,
4481 /*slice=*/mlir::Value{},
4482 std::nullopt);
4485 static fir::ShapeOp genShapeOp(mlir::Location loc, fir::FirOpBuilder &builder,
4486 llvm::ArrayRef<mlir::Value> shape) {
4487 mlir::IndexType idxTy = builder.getIndexType();
4488 llvm::SmallVector<mlir::Value> idxShape;
4489 for (auto s : shape)
4490 idxShape.push_back(builder.createConvert(loc, idxTy, s));
4491 return builder.create<fir::ShapeOp>(loc, idxShape);
4494 fir::ShapeOp genShapeOp(llvm::ArrayRef<mlir::Value> shape) {
4495 return genShapeOp(getLoc(), builder, shape);
4498 //===--------------------------------------------------------------------===//
4499 // Expression traversal and lowering.
4500 //===--------------------------------------------------------------------===//
4502 /// Lower the expression, \p x, in a scalar context.
4503 template <typename A>
4504 ExtValue asScalar(const A &x) {
4505 return ScalarExprLowering{getLoc(), converter, symMap, stmtCtx}.genval(x);
4508 /// Lower the expression, \p x, in a scalar context. If this is an explicit
4509 /// space, the expression may be scalar and refer to an array. We want to
4510 /// raise the array access to array operations in FIR to analyze potential
4511 /// conflicts even when the result is a scalar element.
4512 template <typename A>
4513 ExtValue asScalarArray(const A &x) {
4514 return explicitSpaceIsActive() && !isPointerAssignment()
4515 ? genarr(x)(IterationSpace{})
4516 : asScalar(x);
4519 /// Lower the expression in a scalar context to a memory reference.
4520 template <typename A>
4521 ExtValue asScalarRef(const A &x) {
4522 return ScalarExprLowering{getLoc(), converter, symMap, stmtCtx}.gen(x);
4525 /// Lower an expression without dereferencing any indirection that may be
4526 /// a nullptr (because this is an absent optional or unallocated/disassociated
4527 /// descriptor). The returned expression cannot be addressed directly, it is
4528 /// meant to inquire about its status before addressing the related entity.
4529 template <typename A>
4530 ExtValue asInquired(const A &x) {
4531 return ScalarExprLowering{getLoc(), converter, symMap, stmtCtx}
4532 .lowerIntrinsicArgumentAsInquired(x);
4535 /// Some temporaries are allocated on an element-by-element basis during the
4536 /// array expression evaluation. Collect the cleanups here so the resources
4537 /// can be freed before the next loop iteration, avoiding memory leaks. etc.
4538 Fortran::lower::StatementContext &getElementCtx() {
4539 if (!elementCtx) {
4540 stmtCtx.pushScope();
4541 elementCtx = true;
4543 return stmtCtx;
4546 /// If there were temporaries created for this element evaluation, finalize
4547 /// and deallocate the resources now. This should be done just prior to the
4548 /// fir::ResultOp at the end of the innermost loop.
4549 void finalizeElementCtx() {
4550 if (elementCtx) {
4551 stmtCtx.finalizeAndPop();
4552 elementCtx = false;
4556 /// Lower an elemental function array argument. This ensures array
4557 /// sub-expressions that are not variables and must be passed by address
4558 /// are lowered by value and placed in memory.
4559 template <typename A>
4560 CC genElementalArgument(const A &x) {
4561 // Ensure the returned element is in memory if this is what was requested.
4562 if ((semant == ConstituentSemantics::RefOpaque ||
4563 semant == ConstituentSemantics::DataAddr ||
4564 semant == ConstituentSemantics::ByValueArg)) {
4565 if (!Fortran::evaluate::IsVariable(x)) {
4566 PushSemantics(ConstituentSemantics::DataValue);
4567 CC cc = genarr(x);
4568 mlir::Location loc = getLoc();
4569 if (isParenthesizedVariable(x)) {
4570 // Parenthesised variables are lowered to a reference to the variable
4571 // storage. When passing it as an argument, a copy must be passed.
4572 return [=](IterSpace iters) -> ExtValue {
4573 return createInMemoryScalarCopy(builder, loc, cc(iters));
4576 mlir::Type storageType =
4577 fir::unwrapSequenceType(converter.genType(toEvExpr(x)));
4578 return [=](IterSpace iters) -> ExtValue {
4579 return placeScalarValueInMemory(builder, loc, cc(iters), storageType);
4581 } else if (isArray(x)) {
4582 // An array reference is needed, but the indices used in its path must
4583 // still be retrieved by value.
4584 assert(!nextPathSemant && "Next path semantics already set!");
4585 nextPathSemant = ConstituentSemantics::RefTransparent;
4586 CC cc = genarr(x);
4587 assert(!nextPathSemant && "Next path semantics wasn't used!");
4588 return cc;
4591 return genarr(x);
4594 // A reference to a Fortran elemental intrinsic or intrinsic module procedure.
4595 CC genElementalIntrinsicProcRef(
4596 const Fortran::evaluate::ProcedureRef &procRef,
4597 std::optional<mlir::Type> retTy,
4598 std::optional<const Fortran::evaluate::SpecificIntrinsic> intrinsic =
4599 std::nullopt) {
4601 llvm::SmallVector<CC> operands;
4602 std::string name =
4603 intrinsic ? intrinsic->name
4604 : procRef.proc().GetSymbol()->GetUltimate().name().ToString();
4605 const fir::IntrinsicArgumentLoweringRules *argLowering =
4606 fir::getIntrinsicArgumentLowering(name);
4607 mlir::Location loc = getLoc();
4608 if (intrinsic && Fortran::lower::intrinsicRequiresCustomOptionalHandling(
4609 procRef, *intrinsic, converter)) {
4610 using CcPairT = std::pair<CC, std::optional<mlir::Value>>;
4611 llvm::SmallVector<CcPairT> operands;
4612 auto prepareOptionalArg = [&](const Fortran::lower::SomeExpr &expr) {
4613 if (expr.Rank() == 0) {
4614 ExtValue optionalArg = this->asInquired(expr);
4615 mlir::Value isPresent =
4616 genActualIsPresentTest(builder, loc, optionalArg);
4617 operands.emplace_back(
4618 [=](IterSpace iters) -> ExtValue {
4619 return genLoad(builder, loc, optionalArg);
4621 isPresent);
4622 } else {
4623 auto [cc, isPresent, _] = this->genOptionalArrayFetch(expr);
4624 operands.emplace_back(cc, isPresent);
4627 auto prepareOtherArg = [&](const Fortran::lower::SomeExpr &expr,
4628 fir::LowerIntrinsicArgAs lowerAs) {
4629 assert(lowerAs == fir::LowerIntrinsicArgAs::Value &&
4630 "expect value arguments for elemental intrinsic");
4631 PushSemantics(ConstituentSemantics::RefTransparent);
4632 operands.emplace_back(genElementalArgument(expr), std::nullopt);
4634 Fortran::lower::prepareCustomIntrinsicArgument(
4635 procRef, *intrinsic, retTy, prepareOptionalArg, prepareOtherArg,
4636 converter);
4638 fir::FirOpBuilder *bldr = &converter.getFirOpBuilder();
4639 return [=](IterSpace iters) -> ExtValue {
4640 auto getArgument = [&](std::size_t i, bool) -> ExtValue {
4641 return operands[i].first(iters);
4643 auto isPresent = [&](std::size_t i) -> std::optional<mlir::Value> {
4644 return operands[i].second;
4646 return Fortran::lower::lowerCustomIntrinsic(
4647 *bldr, loc, name, retTy, isPresent, getArgument, operands.size(),
4648 getElementCtx());
4651 /// Otherwise, pre-lower arguments and use intrinsic lowering utility.
4652 for (const auto &arg : llvm::enumerate(procRef.arguments())) {
4653 const auto *expr =
4654 Fortran::evaluate::UnwrapExpr<Fortran::lower::SomeExpr>(arg.value());
4655 if (!expr) {
4656 // Absent optional.
4657 operands.emplace_back([=](IterSpace) { return mlir::Value{}; });
4658 } else if (!argLowering) {
4659 // No argument lowering instruction, lower by value.
4660 PushSemantics(ConstituentSemantics::RefTransparent);
4661 operands.emplace_back(genElementalArgument(*expr));
4662 } else {
4663 // Ad-hoc argument lowering handling.
4664 fir::ArgLoweringRule argRules =
4665 fir::lowerIntrinsicArgumentAs(*argLowering, arg.index());
4666 if (argRules.handleDynamicOptional &&
4667 Fortran::evaluate::MayBePassedAsAbsentOptional(*expr)) {
4668 // Currently, there is not elemental intrinsic that requires lowering
4669 // a potentially absent argument to something else than a value (apart
4670 // from character MAX/MIN that are handled elsewhere.)
4671 if (argRules.lowerAs != fir::LowerIntrinsicArgAs::Value)
4672 TODO(loc, "non trivial optional elemental intrinsic array "
4673 "argument");
4674 PushSemantics(ConstituentSemantics::RefTransparent);
4675 operands.emplace_back(genarrForwardOptionalArgumentToCall(*expr));
4676 continue;
4678 switch (argRules.lowerAs) {
4679 case fir::LowerIntrinsicArgAs::Value: {
4680 PushSemantics(ConstituentSemantics::RefTransparent);
4681 operands.emplace_back(genElementalArgument(*expr));
4682 } break;
4683 case fir::LowerIntrinsicArgAs::Addr: {
4684 // Note: assume does not have Fortran VALUE attribute semantics.
4685 PushSemantics(ConstituentSemantics::RefOpaque);
4686 operands.emplace_back(genElementalArgument(*expr));
4687 } break;
4688 case fir::LowerIntrinsicArgAs::Box: {
4689 PushSemantics(ConstituentSemantics::RefOpaque);
4690 auto lambda = genElementalArgument(*expr);
4691 operands.emplace_back([=](IterSpace iters) {
4692 return builder.createBox(loc, lambda(iters));
4694 } break;
4695 case fir::LowerIntrinsicArgAs::Inquired:
4696 TODO(loc, "intrinsic function with inquired argument");
4697 break;
4702 // Let the intrinsic library lower the intrinsic procedure call
4703 return [=](IterSpace iters) {
4704 llvm::SmallVector<ExtValue> args;
4705 for (const auto &cc : operands)
4706 args.push_back(cc(iters));
4707 return Fortran::lower::genIntrinsicCall(builder, loc, name, retTy, args,
4708 getElementCtx());
4712 /// Lower a procedure reference to a user-defined elemental procedure.
4713 CC genElementalUserDefinedProcRef(
4714 const Fortran::evaluate::ProcedureRef &procRef,
4715 std::optional<mlir::Type> retTy) {
4716 using PassBy = Fortran::lower::CallerInterface::PassEntityBy;
4718 // 10.1.4 p5. Impure elemental procedures must be called in element order.
4719 if (const Fortran::semantics::Symbol *procSym = procRef.proc().GetSymbol())
4720 if (!Fortran::semantics::IsPureProcedure(*procSym))
4721 setUnordered(false);
4723 Fortran::lower::CallerInterface caller(procRef, converter);
4724 llvm::SmallVector<CC> operands;
4725 operands.reserve(caller.getPassedArguments().size());
4726 mlir::Location loc = getLoc();
4727 mlir::FunctionType callSiteType = caller.genFunctionType();
4728 for (const Fortran::lower::CallInterface<
4729 Fortran::lower::CallerInterface>::PassedEntity &arg :
4730 caller.getPassedArguments()) {
4731 // 15.8.3 p1. Elemental procedure with intent(out)/intent(inout)
4732 // arguments must be called in element order.
4733 if (arg.mayBeModifiedByCall())
4734 setUnordered(false);
4735 const auto *actual = arg.entity;
4736 mlir::Type argTy = callSiteType.getInput(arg.firArgument);
4737 if (!actual) {
4738 // Optional dummy argument for which there is no actual argument.
4739 auto absent = builder.create<fir::AbsentOp>(loc, argTy);
4740 operands.emplace_back([=](IterSpace) { return absent; });
4741 continue;
4743 const auto *expr = actual->UnwrapExpr();
4744 if (!expr)
4745 TODO(loc, "assumed type actual argument");
4747 LLVM_DEBUG(expr->AsFortran(llvm::dbgs()
4748 << "argument: " << arg.firArgument << " = [")
4749 << "]\n");
4750 if (arg.isOptional() &&
4751 Fortran::evaluate::MayBePassedAsAbsentOptional(*expr))
4752 TODO(loc,
4753 "passing dynamically optional argument to elemental procedures");
4754 switch (arg.passBy) {
4755 case PassBy::Value: {
4756 // True pass-by-value semantics.
4757 PushSemantics(ConstituentSemantics::RefTransparent);
4758 operands.emplace_back(genElementalArgument(*expr));
4759 } break;
4760 case PassBy::BaseAddressValueAttribute: {
4761 // VALUE attribute or pass-by-reference to a copy semantics. (byval*)
4762 if (isArray(*expr)) {
4763 PushSemantics(ConstituentSemantics::ByValueArg);
4764 operands.emplace_back(genElementalArgument(*expr));
4765 } else {
4766 // Store scalar value in a temp to fulfill VALUE attribute.
4767 mlir::Value val = fir::getBase(asScalar(*expr));
4768 mlir::Value temp =
4769 builder.createTemporary(loc, val.getType(),
4770 llvm::ArrayRef<mlir::NamedAttribute>{
4771 fir::getAdaptToByRefAttr(builder)});
4772 builder.create<fir::StoreOp>(loc, val, temp);
4773 operands.emplace_back(
4774 [=](IterSpace iters) -> ExtValue { return temp; });
4776 } break;
4777 case PassBy::BaseAddress: {
4778 if (isArray(*expr)) {
4779 PushSemantics(ConstituentSemantics::RefOpaque);
4780 operands.emplace_back(genElementalArgument(*expr));
4781 } else {
4782 ExtValue exv = asScalarRef(*expr);
4783 operands.emplace_back([=](IterSpace iters) { return exv; });
4785 } break;
4786 case PassBy::CharBoxValueAttribute: {
4787 if (isArray(*expr)) {
4788 PushSemantics(ConstituentSemantics::DataValue);
4789 auto lambda = genElementalArgument(*expr);
4790 operands.emplace_back([=](IterSpace iters) {
4791 return fir::factory::CharacterExprHelper{builder, loc}
4792 .createTempFrom(lambda(iters));
4794 } else {
4795 fir::factory::CharacterExprHelper helper(builder, loc);
4796 fir::CharBoxValue argVal = helper.createTempFrom(asScalarRef(*expr));
4797 operands.emplace_back(
4798 [=](IterSpace iters) -> ExtValue { return argVal; });
4800 } break;
4801 case PassBy::BoxChar: {
4802 PushSemantics(ConstituentSemantics::RefOpaque);
4803 operands.emplace_back(genElementalArgument(*expr));
4804 } break;
4805 case PassBy::AddressAndLength:
4806 // PassBy::AddressAndLength is only used for character results. Results
4807 // are not handled here.
4808 fir::emitFatalError(
4809 loc, "unexpected PassBy::AddressAndLength in elemental call");
4810 break;
4811 case PassBy::CharProcTuple: {
4812 ExtValue argRef = asScalarRef(*expr);
4813 mlir::Value tuple = createBoxProcCharTuple(
4814 converter, argTy, fir::getBase(argRef), fir::getLen(argRef));
4815 operands.emplace_back(
4816 [=](IterSpace iters) -> ExtValue { return tuple; });
4817 } break;
4818 case PassBy::Box:
4819 case PassBy::MutableBox:
4820 // Handle polymorphic passed object.
4821 if (fir::isPolymorphicType(argTy)) {
4822 if (isArray(*expr)) {
4823 ExtValue exv = asScalarRef(*expr);
4824 mlir::Value sourceBox;
4825 if (fir::isPolymorphicType(fir::getBase(exv).getType()))
4826 sourceBox = fir::getBase(exv);
4827 mlir::Type baseTy =
4828 fir::dyn_cast_ptrOrBoxEleTy(fir::getBase(exv).getType());
4829 mlir::Type innerTy = fir::unwrapSequenceType(baseTy);
4830 operands.emplace_back([=](IterSpace iters) -> ExtValue {
4831 mlir::Value coord = builder.create<fir::CoordinateOp>(
4832 loc, fir::ReferenceType::get(innerTy), fir::getBase(exv),
4833 iters.iterVec());
4834 mlir::Value empty;
4835 mlir::ValueRange emptyRange;
4836 return builder.create<fir::EmboxOp>(
4837 loc, fir::ClassType::get(innerTy), coord, empty, empty,
4838 emptyRange, sourceBox);
4840 } else {
4841 ExtValue exv = asScalarRef(*expr);
4842 if (mlir::isa<fir::BaseBoxType>(fir::getBase(exv).getType())) {
4843 operands.emplace_back(
4844 [=](IterSpace iters) -> ExtValue { return exv; });
4845 } else {
4846 mlir::Type baseTy =
4847 fir::dyn_cast_ptrOrBoxEleTy(fir::getBase(exv).getType());
4848 operands.emplace_back([=](IterSpace iters) -> ExtValue {
4849 mlir::Value empty;
4850 mlir::ValueRange emptyRange;
4851 return builder.create<fir::EmboxOp>(
4852 loc, fir::ClassType::get(baseTy), fir::getBase(exv), empty,
4853 empty, emptyRange);
4857 break;
4859 // See C15100 and C15101
4860 fir::emitFatalError(loc, "cannot be POINTER, ALLOCATABLE");
4861 case PassBy::BoxProcRef:
4862 // Procedure pointer: no action here.
4863 break;
4867 if (caller.getIfIndirectCall())
4868 fir::emitFatalError(loc, "cannot be indirect call");
4870 // The lambda is mutable so that `caller` copy can be modified inside it.
4871 return [=,
4872 caller = std::move(caller)](IterSpace iters) mutable -> ExtValue {
4873 for (const auto &[cc, argIface] :
4874 llvm::zip(operands, caller.getPassedArguments())) {
4875 auto exv = cc(iters);
4876 auto arg = exv.match(
4877 [&](const fir::CharBoxValue &cb) -> mlir::Value {
4878 return fir::factory::CharacterExprHelper{builder, loc}
4879 .createEmbox(cb);
4881 [&](const auto &) { return fir::getBase(exv); });
4882 caller.placeInput(argIface, arg);
4884 return Fortran::lower::genCallOpAndResult(loc, converter, symMap,
4885 getElementCtx(), caller,
4886 callSiteType, retTy)
4887 .first;
4891 /// Lower TRANSPOSE call without using runtime TRANSPOSE.
4892 /// Return continuation for generating the TRANSPOSE result.
4893 /// The continuation just swaps the iteration space before
4894 /// invoking continuation for the argument.
4895 CC genTransposeProcRef(const Fortran::evaluate::ProcedureRef &procRef) {
4896 assert(procRef.arguments().size() == 1 &&
4897 "TRANSPOSE must have one argument.");
4898 const auto *argExpr = procRef.arguments()[0].value().UnwrapExpr();
4899 assert(argExpr);
4901 llvm::SmallVector<mlir::Value> savedDestShape = destShape;
4902 assert((destShape.empty() || destShape.size() == 2) &&
4903 "TRANSPOSE destination must have rank 2.");
4905 if (!savedDestShape.empty())
4906 std::swap(destShape[0], destShape[1]);
4908 PushSemantics(ConstituentSemantics::RefTransparent);
4909 llvm::SmallVector<CC> operands{genElementalArgument(*argExpr)};
4911 if (!savedDestShape.empty()) {
4912 // If destShape was set before transpose lowering, then
4913 // restore it. Otherwise, ...
4914 destShape = savedDestShape;
4915 } else if (!destShape.empty()) {
4916 // ... if destShape has been set from the argument lowering,
4917 // then reverse it.
4918 assert(destShape.size() == 2 &&
4919 "TRANSPOSE destination must have rank 2.");
4920 std::swap(destShape[0], destShape[1]);
4923 return [=](IterSpace iters) {
4924 assert(iters.iterVec().size() == 2 &&
4925 "TRANSPOSE expects 2D iterations space.");
4926 IterationSpace newIters(iters, {iters.iterValue(1), iters.iterValue(0)});
4927 return operands.front()(newIters);
4931 /// Generate a procedure reference. This code is shared for both functions and
4932 /// subroutines, the difference being reflected by `retTy`.
4933 CC genProcRef(const Fortran::evaluate::ProcedureRef &procRef,
4934 std::optional<mlir::Type> retTy) {
4935 mlir::Location loc = getLoc();
4936 setLoweredProcRef(&procRef);
4938 if (isOptimizableTranspose(procRef, converter))
4939 return genTransposeProcRef(procRef);
4941 if (procRef.IsElemental()) {
4942 if (const Fortran::evaluate::SpecificIntrinsic *intrin =
4943 procRef.proc().GetSpecificIntrinsic()) {
4944 // All elemental intrinsic functions are pure and cannot modify their
4945 // arguments. The only elemental subroutine, MVBITS has an Intent(inout)
4946 // argument. So for this last one, loops must be in element order
4947 // according to 15.8.3 p1.
4948 if (!retTy)
4949 setUnordered(false);
4951 // Elemental intrinsic call.
4952 // The intrinsic procedure is called once per element of the array.
4953 return genElementalIntrinsicProcRef(procRef, retTy, *intrin);
4955 if (Fortran::lower::isIntrinsicModuleProcRef(procRef))
4956 return genElementalIntrinsicProcRef(procRef, retTy);
4957 if (ScalarExprLowering::isStatementFunctionCall(procRef))
4958 fir::emitFatalError(loc, "statement function cannot be elemental");
4960 // Elemental call.
4961 // The procedure is called once per element of the array argument(s).
4962 return genElementalUserDefinedProcRef(procRef, retTy);
4965 // Transformational call.
4966 // The procedure is called once and produces a value of rank > 0.
4967 if (const Fortran::evaluate::SpecificIntrinsic *intrinsic =
4968 procRef.proc().GetSpecificIntrinsic()) {
4969 if (explicitSpaceIsActive() && procRef.Rank() == 0) {
4970 // Elide any implicit loop iters.
4971 return [=, &procRef](IterSpace) {
4972 return ScalarExprLowering{loc, converter, symMap, stmtCtx}
4973 .genIntrinsicRef(procRef, retTy, *intrinsic);
4976 return genarr(
4977 ScalarExprLowering{loc, converter, symMap, stmtCtx}.genIntrinsicRef(
4978 procRef, retTy, *intrinsic));
4981 const bool isPtrAssn = isPointerAssignment();
4982 if (explicitSpaceIsActive() && procRef.Rank() == 0) {
4983 // Elide any implicit loop iters.
4984 return [=, &procRef](IterSpace) {
4985 ScalarExprLowering sel(loc, converter, symMap, stmtCtx);
4986 return isPtrAssn ? sel.genRawProcedureRef(procRef, retTy)
4987 : sel.genProcedureRef(procRef, retTy);
4990 // In the default case, the call can be hoisted out of the loop nest. Apply
4991 // the iterations to the result, which may be an array value.
4992 ScalarExprLowering sel(loc, converter, symMap, stmtCtx);
4993 auto exv = isPtrAssn ? sel.genRawProcedureRef(procRef, retTy)
4994 : sel.genProcedureRef(procRef, retTy);
4995 return genarr(exv);
4998 CC genarr(const Fortran::evaluate::ProcedureDesignator &) {
4999 TODO(getLoc(), "procedure designator");
5001 CC genarr(const Fortran::evaluate::ProcedureRef &x) {
5002 if (x.hasAlternateReturns())
5003 fir::emitFatalError(getLoc(),
5004 "array procedure reference with alt-return");
5005 return genProcRef(x, std::nullopt);
5007 template <typename A>
5008 CC genScalarAndForwardValue(const A &x) {
5009 ExtValue result = asScalar(x);
5010 return [=](IterSpace) { return result; };
5012 template <typename A, typename = std::enable_if_t<Fortran::common::HasMember<
5013 A, Fortran::evaluate::TypelessExpression>>>
5014 CC genarr(const A &x) {
5015 return genScalarAndForwardValue(x);
5018 template <typename A>
5019 CC genarr(const Fortran::evaluate::Expr<A> &x) {
5020 LLVM_DEBUG(Fortran::lower::DumpEvaluateExpr::dump(llvm::dbgs(), x));
5021 if (isArray(x) || (explicitSpaceIsActive() && isLeftHandSide()) ||
5022 isElementalProcWithArrayArgs(x))
5023 return Fortran::common::visit([&](const auto &e) { return genarr(e); },
5024 x.u);
5025 if (explicitSpaceIsActive()) {
5026 assert(!isArray(x) && !isLeftHandSide());
5027 auto cc =
5028 Fortran::common::visit([&](const auto &e) { return genarr(e); }, x.u);
5029 auto result = cc(IterationSpace{});
5030 return [=](IterSpace) { return result; };
5032 return genScalarAndForwardValue(x);
5035 // Converting a value of memory bound type requires creating a temp and
5036 // copying the value.
5037 static ExtValue convertAdjustedType(fir::FirOpBuilder &builder,
5038 mlir::Location loc, mlir::Type toType,
5039 const ExtValue &exv) {
5040 return exv.match(
5041 [&](const fir::CharBoxValue &cb) -> ExtValue {
5042 mlir::Value len = cb.getLen();
5043 auto mem =
5044 builder.create<fir::AllocaOp>(loc, toType, mlir::ValueRange{len});
5045 fir::CharBoxValue result(mem, len);
5046 fir::factory::CharacterExprHelper{builder, loc}.createAssign(
5047 ExtValue{result}, exv);
5048 return result;
5050 [&](const auto &) -> ExtValue {
5051 fir::emitFatalError(loc, "convert on adjusted extended value");
5054 template <Fortran::common::TypeCategory TC1, int KIND,
5055 Fortran::common::TypeCategory TC2>
5056 CC genarr(const Fortran::evaluate::Convert<Fortran::evaluate::Type<TC1, KIND>,
5057 TC2> &x) {
5058 mlir::Location loc = getLoc();
5059 auto lambda = genarr(x.left());
5060 mlir::Type ty = converter.genType(TC1, KIND);
5061 return [=](IterSpace iters) -> ExtValue {
5062 auto exv = lambda(iters);
5063 mlir::Value val = fir::getBase(exv);
5064 auto valTy = val.getType();
5065 if (elementTypeWasAdjusted(valTy) &&
5066 !(fir::isa_ref_type(valTy) && fir::isa_integer(ty)))
5067 return convertAdjustedType(builder, loc, ty, exv);
5068 return builder.createConvert(loc, ty, val);
5072 template <int KIND>
5073 CC genarr(const Fortran::evaluate::ComplexComponent<KIND> &x) {
5074 mlir::Location loc = getLoc();
5075 auto lambda = genarr(x.left());
5076 bool isImagPart = x.isImaginaryPart;
5077 return [=](IterSpace iters) -> ExtValue {
5078 mlir::Value lhs = fir::getBase(lambda(iters));
5079 return fir::factory::Complex{builder, loc}.extractComplexPart(lhs,
5080 isImagPart);
5084 template <typename T>
5085 CC genarr(const Fortran::evaluate::Parentheses<T> &x) {
5086 mlir::Location loc = getLoc();
5087 if (isReferentiallyOpaque()) {
5088 // Context is a call argument in, for example, an elemental procedure
5089 // call. TODO: all array arguments should use array_load, array_access,
5090 // array_amend, and INTENT(OUT), INTENT(INOUT) arguments should have
5091 // array_merge_store ops.
5092 TODO(loc, "parentheses on argument in elemental call");
5094 auto f = genarr(x.left());
5095 return [=](IterSpace iters) -> ExtValue {
5096 auto val = f(iters);
5097 mlir::Value base = fir::getBase(val);
5098 auto newBase =
5099 builder.create<fir::NoReassocOp>(loc, base.getType(), base);
5100 return fir::substBase(val, newBase);
5103 template <int KIND>
5104 CC genarr(const Fortran::evaluate::Negate<Fortran::evaluate::Type<
5105 Fortran::common::TypeCategory::Integer, KIND>> &x) {
5106 mlir::Location loc = getLoc();
5107 auto f = genarr(x.left());
5108 return [=](IterSpace iters) -> ExtValue {
5109 mlir::Value val = fir::getBase(f(iters));
5110 mlir::Type ty =
5111 converter.genType(Fortran::common::TypeCategory::Integer, KIND);
5112 mlir::Value zero = builder.createIntegerConstant(loc, ty, 0);
5113 return builder.create<mlir::arith::SubIOp>(loc, zero, val);
5116 template <int KIND>
5117 CC genarr(const Fortran::evaluate::Negate<Fortran::evaluate::Type<
5118 Fortran::common::TypeCategory::Real, KIND>> &x) {
5119 mlir::Location loc = getLoc();
5120 auto f = genarr(x.left());
5121 return [=](IterSpace iters) -> ExtValue {
5122 return builder.create<mlir::arith::NegFOp>(loc, fir::getBase(f(iters)));
5125 template <int KIND>
5126 CC genarr(const Fortran::evaluate::Negate<Fortran::evaluate::Type<
5127 Fortran::common::TypeCategory::Complex, KIND>> &x) {
5128 mlir::Location loc = getLoc();
5129 auto f = genarr(x.left());
5130 return [=](IterSpace iters) -> ExtValue {
5131 return builder.create<fir::NegcOp>(loc, fir::getBase(f(iters)));
5135 //===--------------------------------------------------------------------===//
5136 // Binary elemental ops
5137 //===--------------------------------------------------------------------===//
5139 template <typename OP, typename A>
5140 CC createBinaryOp(const A &evEx) {
5141 mlir::Location loc = getLoc();
5142 auto lambda = genarr(evEx.left());
5143 auto rf = genarr(evEx.right());
5144 return [=](IterSpace iters) -> ExtValue {
5145 mlir::Value left = fir::getBase(lambda(iters));
5146 mlir::Value right = fir::getBase(rf(iters));
5147 return builder.create<OP>(loc, left, right);
5151 #undef GENBIN
5152 #define GENBIN(GenBinEvOp, GenBinTyCat, GenBinFirOp) \
5153 template <int KIND> \
5154 CC genarr(const Fortran::evaluate::GenBinEvOp<Fortran::evaluate::Type< \
5155 Fortran::common::TypeCategory::GenBinTyCat, KIND>> &x) { \
5156 return createBinaryOp<GenBinFirOp>(x); \
5159 GENBIN(Add, Integer, mlir::arith::AddIOp)
5160 GENBIN(Add, Real, mlir::arith::AddFOp)
5161 GENBIN(Add, Complex, fir::AddcOp)
5162 GENBIN(Subtract, Integer, mlir::arith::SubIOp)
5163 GENBIN(Subtract, Real, mlir::arith::SubFOp)
5164 GENBIN(Subtract, Complex, fir::SubcOp)
5165 GENBIN(Multiply, Integer, mlir::arith::MulIOp)
5166 GENBIN(Multiply, Real, mlir::arith::MulFOp)
5167 GENBIN(Multiply, Complex, fir::MulcOp)
5168 GENBIN(Divide, Integer, mlir::arith::DivSIOp)
5169 GENBIN(Divide, Real, mlir::arith::DivFOp)
5171 template <int KIND>
5172 CC genarr(const Fortran::evaluate::Divide<Fortran::evaluate::Type<
5173 Fortran::common::TypeCategory::Complex, KIND>> &x) {
5174 mlir::Location loc = getLoc();
5175 mlir::Type ty =
5176 converter.genType(Fortran::common::TypeCategory::Complex, KIND);
5177 auto lf = genarr(x.left());
5178 auto rf = genarr(x.right());
5179 return [=](IterSpace iters) -> ExtValue {
5180 mlir::Value lhs = fir::getBase(lf(iters));
5181 mlir::Value rhs = fir::getBase(rf(iters));
5182 return fir::genDivC(builder, loc, ty, lhs, rhs);
5186 template <Fortran::common::TypeCategory TC, int KIND>
5187 CC genarr(
5188 const Fortran::evaluate::Power<Fortran::evaluate::Type<TC, KIND>> &x) {
5189 mlir::Location loc = getLoc();
5190 mlir::Type ty = converter.genType(TC, KIND);
5191 auto lf = genarr(x.left());
5192 auto rf = genarr(x.right());
5193 return [=](IterSpace iters) -> ExtValue {
5194 mlir::Value lhs = fir::getBase(lf(iters));
5195 mlir::Value rhs = fir::getBase(rf(iters));
5196 return fir::genPow(builder, loc, ty, lhs, rhs);
5199 template <Fortran::common::TypeCategory TC, int KIND>
5200 CC genarr(
5201 const Fortran::evaluate::Extremum<Fortran::evaluate::Type<TC, KIND>> &x) {
5202 mlir::Location loc = getLoc();
5203 auto lf = genarr(x.left());
5204 auto rf = genarr(x.right());
5205 switch (x.ordering) {
5206 case Fortran::evaluate::Ordering::Greater:
5207 return [=](IterSpace iters) -> ExtValue {
5208 mlir::Value lhs = fir::getBase(lf(iters));
5209 mlir::Value rhs = fir::getBase(rf(iters));
5210 return fir::genMax(builder, loc, llvm::ArrayRef<mlir::Value>{lhs, rhs});
5212 case Fortran::evaluate::Ordering::Less:
5213 return [=](IterSpace iters) -> ExtValue {
5214 mlir::Value lhs = fir::getBase(lf(iters));
5215 mlir::Value rhs = fir::getBase(rf(iters));
5216 return fir::genMin(builder, loc, llvm::ArrayRef<mlir::Value>{lhs, rhs});
5218 case Fortran::evaluate::Ordering::Equal:
5219 llvm_unreachable("Equal is not a valid ordering in this context");
5221 llvm_unreachable("unknown ordering");
5223 template <Fortran::common::TypeCategory TC, int KIND>
5224 CC genarr(
5225 const Fortran::evaluate::RealToIntPower<Fortran::evaluate::Type<TC, KIND>>
5226 &x) {
5227 mlir::Location loc = getLoc();
5228 auto ty = converter.genType(TC, KIND);
5229 auto lf = genarr(x.left());
5230 auto rf = genarr(x.right());
5231 return [=](IterSpace iters) {
5232 mlir::Value lhs = fir::getBase(lf(iters));
5233 mlir::Value rhs = fir::getBase(rf(iters));
5234 return fir::genPow(builder, loc, ty, lhs, rhs);
5237 template <int KIND>
5238 CC genarr(const Fortran::evaluate::ComplexConstructor<KIND> &x) {
5239 mlir::Location loc = getLoc();
5240 auto lf = genarr(x.left());
5241 auto rf = genarr(x.right());
5242 return [=](IterSpace iters) -> ExtValue {
5243 mlir::Value lhs = fir::getBase(lf(iters));
5244 mlir::Value rhs = fir::getBase(rf(iters));
5245 return fir::factory::Complex{builder, loc}.createComplex(KIND, lhs, rhs);
5249 /// Fortran's concatenation operator `//`.
5250 template <int KIND>
5251 CC genarr(const Fortran::evaluate::Concat<KIND> &x) {
5252 mlir::Location loc = getLoc();
5253 auto lf = genarr(x.left());
5254 auto rf = genarr(x.right());
5255 return [=](IterSpace iters) -> ExtValue {
5256 auto lhs = lf(iters);
5257 auto rhs = rf(iters);
5258 const fir::CharBoxValue *lchr = lhs.getCharBox();
5259 const fir::CharBoxValue *rchr = rhs.getCharBox();
5260 if (lchr && rchr) {
5261 return fir::factory::CharacterExprHelper{builder, loc}
5262 .createConcatenate(*lchr, *rchr);
5264 TODO(loc, "concat on unexpected extended values");
5265 return mlir::Value{};
5269 template <int KIND>
5270 CC genarr(const Fortran::evaluate::SetLength<KIND> &x) {
5271 auto lf = genarr(x.left());
5272 mlir::Value rhs = fir::getBase(asScalar(x.right()));
5273 fir::CharBoxValue temp =
5274 fir::factory::CharacterExprHelper(builder, getLoc())
5275 .createCharacterTemp(
5276 fir::CharacterType::getUnknownLen(builder.getContext(), KIND),
5277 rhs);
5278 return [=](IterSpace iters) -> ExtValue {
5279 fir::factory::CharacterExprHelper(builder, getLoc())
5280 .createAssign(temp, lf(iters));
5281 return temp;
5285 template <typename T>
5286 CC genarr(const Fortran::evaluate::Constant<T> &x) {
5287 if (x.Rank() == 0)
5288 return genScalarAndForwardValue(x);
5289 return genarr(Fortran::lower::convertConstant(
5290 converter, getLoc(), x,
5291 /*outlineBigConstantsInReadOnlyMemory=*/true));
5294 //===--------------------------------------------------------------------===//
5295 // A vector subscript expression may be wrapped with a cast to INTEGER*8.
5296 // Get rid of it here so the vector can be loaded. Add it back when
5297 // generating the elemental evaluation (inside the loop nest).
5299 static Fortran::lower::SomeExpr
5300 ignoreEvConvert(const Fortran::evaluate::Expr<Fortran::evaluate::Type<
5301 Fortran::common::TypeCategory::Integer, 8>> &x) {
5302 return Fortran::common::visit(
5303 [&](const auto &v) { return ignoreEvConvert(v); }, x.u);
5305 template <Fortran::common::TypeCategory FROM>
5306 static Fortran::lower::SomeExpr ignoreEvConvert(
5307 const Fortran::evaluate::Convert<
5308 Fortran::evaluate::Type<Fortran::common::TypeCategory::Integer, 8>,
5309 FROM> &x) {
5310 return toEvExpr(x.left());
5312 template <typename A>
5313 static Fortran::lower::SomeExpr ignoreEvConvert(const A &x) {
5314 return toEvExpr(x);
5317 //===--------------------------------------------------------------------===//
5318 // Get the `Se::Symbol*` for the subscript expression, `x`. This symbol can
5319 // be used to determine the lbound, ubound of the vector.
5321 template <typename A>
5322 static const Fortran::semantics::Symbol *
5323 extractSubscriptSymbol(const Fortran::evaluate::Expr<A> &x) {
5324 return Fortran::common::visit(
5325 [&](const auto &v) { return extractSubscriptSymbol(v); }, x.u);
5327 template <typename A>
5328 static const Fortran::semantics::Symbol *
5329 extractSubscriptSymbol(const Fortran::evaluate::Designator<A> &x) {
5330 return Fortran::evaluate::UnwrapWholeSymbolDataRef(x);
5332 template <typename A>
5333 static const Fortran::semantics::Symbol *extractSubscriptSymbol(const A &x) {
5334 return nullptr;
5337 //===--------------------------------------------------------------------===//
5339 /// Get the declared lower bound value of the array `x` in dimension `dim`.
5340 /// The argument `one` must be an ssa-value for the constant 1.
5341 mlir::Value getLBound(const ExtValue &x, unsigned dim, mlir::Value one) {
5342 return fir::factory::readLowerBound(builder, getLoc(), x, dim, one);
5345 /// Get the declared upper bound value of the array `x` in dimension `dim`.
5346 /// The argument `one` must be an ssa-value for the constant 1.
5347 mlir::Value getUBound(const ExtValue &x, unsigned dim, mlir::Value one) {
5348 mlir::Location loc = getLoc();
5349 mlir::Value lb = getLBound(x, dim, one);
5350 mlir::Value extent = fir::factory::readExtent(builder, loc, x, dim);
5351 auto add = builder.create<mlir::arith::AddIOp>(loc, lb, extent);
5352 return builder.create<mlir::arith::SubIOp>(loc, add, one);
5355 /// Return the extent of the boxed array `x` in dimesion `dim`.
5356 mlir::Value getExtent(const ExtValue &x, unsigned dim) {
5357 return fir::factory::readExtent(builder, getLoc(), x, dim);
5360 template <typename A>
5361 ExtValue genArrayBase(const A &base) {
5362 ScalarExprLowering sel{getLoc(), converter, symMap, stmtCtx};
5363 return base.IsSymbol() ? sel.gen(getFirstSym(base))
5364 : sel.gen(base.GetComponent());
5367 template <typename A>
5368 bool hasEvArrayRef(const A &x) {
5369 struct HasEvArrayRefHelper
5370 : public Fortran::evaluate::AnyTraverse<HasEvArrayRefHelper> {
5371 HasEvArrayRefHelper()
5372 : Fortran::evaluate::AnyTraverse<HasEvArrayRefHelper>(*this) {}
5373 using Fortran::evaluate::AnyTraverse<HasEvArrayRefHelper>::operator();
5374 bool operator()(const Fortran::evaluate::ArrayRef &) const {
5375 return true;
5377 } helper;
5378 return helper(x);
5381 CC genVectorSubscriptArrayFetch(const Fortran::lower::SomeExpr &expr,
5382 std::size_t dim) {
5383 PushSemantics(ConstituentSemantics::RefTransparent);
5384 auto saved = Fortran::common::ScopedSet(explicitSpace, nullptr);
5385 llvm::SmallVector<mlir::Value> savedDestShape = destShape;
5386 destShape.clear();
5387 auto result = genarr(expr);
5388 if (destShape.empty())
5389 TODO(getLoc(), "expected vector to have an extent");
5390 assert(destShape.size() == 1 && "vector has rank > 1");
5391 if (destShape[0] != savedDestShape[dim]) {
5392 // Not the same, so choose the smaller value.
5393 mlir::Location loc = getLoc();
5394 auto cmp = builder.create<mlir::arith::CmpIOp>(
5395 loc, mlir::arith::CmpIPredicate::sgt, destShape[0],
5396 savedDestShape[dim]);
5397 auto sel = builder.create<mlir::arith::SelectOp>(
5398 loc, cmp, savedDestShape[dim], destShape[0]);
5399 savedDestShape[dim] = sel;
5400 destShape = savedDestShape;
5402 return result;
5405 /// Generate an access by vector subscript using the index in the iteration
5406 /// vector at `dim`.
5407 mlir::Value genAccessByVector(mlir::Location loc, CC genArrFetch,
5408 IterSpace iters, std::size_t dim) {
5409 IterationSpace vecIters(iters,
5410 llvm::ArrayRef<mlir::Value>{iters.iterValue(dim)});
5411 fir::ExtendedValue fetch = genArrFetch(vecIters);
5412 mlir::IndexType idxTy = builder.getIndexType();
5413 return builder.createConvert(loc, idxTy, fir::getBase(fetch));
5416 /// When we have an array reference, the expressions specified in each
5417 /// dimension may be slice operations (e.g. `i:j:k`), vectors, or simple
5418 /// (loop-invarianet) scalar expressions. This returns the base entity, the
5419 /// resulting type, and a continuation to adjust the default iteration space.
5420 void genSliceIndices(ComponentPath &cmptData, const ExtValue &arrayExv,
5421 const Fortran::evaluate::ArrayRef &x, bool atBase) {
5422 mlir::Location loc = getLoc();
5423 mlir::IndexType idxTy = builder.getIndexType();
5424 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
5425 llvm::SmallVector<mlir::Value> &trips = cmptData.trips;
5426 LLVM_DEBUG(llvm::dbgs() << "array: " << arrayExv << '\n');
5427 auto &pc = cmptData.pc;
5428 const bool useTripsForSlice = !explicitSpaceIsActive();
5429 const bool createDestShape = destShape.empty();
5430 bool useSlice = false;
5431 std::size_t shapeIndex = 0;
5432 for (auto sub : llvm::enumerate(x.subscript())) {
5433 const std::size_t subsIndex = sub.index();
5434 Fortran::common::visit(
5435 Fortran::common::visitors{
5436 [&](const Fortran::evaluate::Triplet &t) {
5437 mlir::Value lowerBound;
5438 if (auto optLo = t.lower())
5439 lowerBound = fir::getBase(asScalarArray(*optLo));
5440 else
5441 lowerBound = getLBound(arrayExv, subsIndex, one);
5442 lowerBound = builder.createConvert(loc, idxTy, lowerBound);
5443 mlir::Value stride = fir::getBase(asScalarArray(t.stride()));
5444 stride = builder.createConvert(loc, idxTy, stride);
5445 if (useTripsForSlice || createDestShape) {
5446 // Generate a slice operation for the triplet. The first and
5447 // second position of the triplet may be omitted, and the
5448 // declared lbound and/or ubound expression values,
5449 // respectively, should be used instead.
5450 trips.push_back(lowerBound);
5451 mlir::Value upperBound;
5452 if (auto optUp = t.upper())
5453 upperBound = fir::getBase(asScalarArray(*optUp));
5454 else
5455 upperBound = getUBound(arrayExv, subsIndex, one);
5456 upperBound = builder.createConvert(loc, idxTy, upperBound);
5457 trips.push_back(upperBound);
5458 trips.push_back(stride);
5459 if (createDestShape) {
5460 auto extent = builder.genExtentFromTriplet(
5461 loc, lowerBound, upperBound, stride, idxTy);
5462 destShape.push_back(extent);
5464 useSlice = true;
5466 if (!useTripsForSlice) {
5467 auto currentPC = pc;
5468 pc = [=](IterSpace iters) {
5469 IterationSpace newIters = currentPC(iters);
5470 mlir::Value impliedIter = newIters.iterValue(subsIndex);
5471 // FIXME: must use the lower bound of this component.
5472 auto arrLowerBound =
5473 atBase ? getLBound(arrayExv, subsIndex, one) : one;
5474 auto initial = builder.create<mlir::arith::SubIOp>(
5475 loc, lowerBound, arrLowerBound);
5476 auto prod = builder.create<mlir::arith::MulIOp>(
5477 loc, impliedIter, stride);
5478 auto result =
5479 builder.create<mlir::arith::AddIOp>(loc, initial, prod);
5480 newIters.setIndexValue(subsIndex, result);
5481 return newIters;
5484 shapeIndex++;
5486 [&](const Fortran::evaluate::IndirectSubscriptIntegerExpr &ie) {
5487 const auto &e = ie.value(); // dereference
5488 if (isArray(e)) {
5489 // This is a vector subscript. Use the index values as read
5490 // from a vector to determine the temporary array value.
5491 // Note: 9.5.3.3.3(3) specifies undefined behavior for
5492 // multiple updates to any specific array element through a
5493 // vector subscript with replicated values.
5494 assert(!isBoxValue() &&
5495 "fir.box cannot be created with vector subscripts");
5496 // TODO: Avoid creating a new evaluate::Expr here
5497 auto arrExpr = ignoreEvConvert(e);
5498 if (createDestShape) {
5499 destShape.push_back(fir::factory::getExtentAtDimension(
5500 loc, builder, arrayExv, subsIndex));
5502 auto genArrFetch =
5503 genVectorSubscriptArrayFetch(arrExpr, shapeIndex);
5504 auto currentPC = pc;
5505 pc = [=](IterSpace iters) {
5506 IterationSpace newIters = currentPC(iters);
5507 auto val = genAccessByVector(loc, genArrFetch, newIters,
5508 subsIndex);
5509 // Value read from vector subscript array and normalized
5510 // using the base array's lower bound value.
5511 mlir::Value lb = fir::factory::readLowerBound(
5512 builder, loc, arrayExv, subsIndex, one);
5513 auto origin = builder.create<mlir::arith::SubIOp>(
5514 loc, idxTy, val, lb);
5515 newIters.setIndexValue(subsIndex, origin);
5516 return newIters;
5518 if (useTripsForSlice) {
5519 LLVM_ATTRIBUTE_UNUSED auto vectorSubscriptShape =
5520 getShape(arrayOperands.back());
5521 auto undef = builder.create<fir::UndefOp>(loc, idxTy);
5522 trips.push_back(undef);
5523 trips.push_back(undef);
5524 trips.push_back(undef);
5526 shapeIndex++;
5527 } else {
5528 // This is a regular scalar subscript.
5529 if (useTripsForSlice) {
5530 // A regular scalar index, which does not yield an array
5531 // section. Use a degenerate slice operation
5532 // `(e:undef:undef)` in this dimension as a placeholder.
5533 // This does not necessarily change the rank of the original
5534 // array, so the iteration space must also be extended to
5535 // include this expression in this dimension to adjust to
5536 // the array's declared rank.
5537 mlir::Value v = fir::getBase(asScalarArray(e));
5538 trips.push_back(v);
5539 auto undef = builder.create<fir::UndefOp>(loc, idxTy);
5540 trips.push_back(undef);
5541 trips.push_back(undef);
5542 auto currentPC = pc;
5543 // Cast `e` to index type.
5544 mlir::Value iv = builder.createConvert(loc, idxTy, v);
5545 // Normalize `e` by subtracting the declared lbound.
5546 mlir::Value lb = fir::factory::readLowerBound(
5547 builder, loc, arrayExv, subsIndex, one);
5548 mlir::Value ivAdj =
5549 builder.create<mlir::arith::SubIOp>(loc, idxTy, iv, lb);
5550 // Add lbound adjusted value of `e` to the iteration vector
5551 // (except when creating a box because the iteration vector
5552 // is empty).
5553 if (!isBoxValue())
5554 pc = [=](IterSpace iters) {
5555 IterationSpace newIters = currentPC(iters);
5556 newIters.insertIndexValue(subsIndex, ivAdj);
5557 return newIters;
5559 } else {
5560 auto currentPC = pc;
5561 mlir::Value newValue = fir::getBase(asScalarArray(e));
5562 mlir::Value result =
5563 builder.createConvert(loc, idxTy, newValue);
5564 mlir::Value lb = fir::factory::readLowerBound(
5565 builder, loc, arrayExv, subsIndex, one);
5566 result = builder.create<mlir::arith::SubIOp>(loc, idxTy,
5567 result, lb);
5568 pc = [=](IterSpace iters) {
5569 IterationSpace newIters = currentPC(iters);
5570 newIters.insertIndexValue(subsIndex, result);
5571 return newIters;
5576 sub.value().u);
5578 if (!useSlice)
5579 trips.clear();
5582 static mlir::Type unwrapBoxEleTy(mlir::Type ty) {
5583 if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(ty))
5584 return fir::unwrapRefType(boxTy.getEleTy());
5585 return ty;
5588 llvm::SmallVector<mlir::Value> getShape(mlir::Type ty) {
5589 llvm::SmallVector<mlir::Value> result;
5590 ty = unwrapBoxEleTy(ty);
5591 mlir::Location loc = getLoc();
5592 mlir::IndexType idxTy = builder.getIndexType();
5593 for (auto extent : mlir::cast<fir::SequenceType>(ty).getShape()) {
5594 auto v = extent == fir::SequenceType::getUnknownExtent()
5595 ? builder.create<fir::UndefOp>(loc, idxTy).getResult()
5596 : builder.createIntegerConstant(loc, idxTy, extent);
5597 result.push_back(v);
5599 return result;
5602 CC genarr(const Fortran::semantics::SymbolRef &sym,
5603 ComponentPath &components) {
5604 return genarr(sym.get(), components);
5607 ExtValue abstractArrayExtValue(mlir::Value val, mlir::Value len = {}) {
5608 return convertToArrayBoxValue(getLoc(), builder, val, len);
5611 CC genarr(const ExtValue &extMemref) {
5612 ComponentPath dummy(/*isImplicit=*/true);
5613 return genarr(extMemref, dummy);
5616 // If the slice values are given then use them. Otherwise, generate triples
5617 // that cover the entire shape specified by \p shapeVal.
5618 inline llvm::SmallVector<mlir::Value>
5619 padSlice(llvm::ArrayRef<mlir::Value> triples, mlir::Value shapeVal) {
5620 llvm::SmallVector<mlir::Value> result;
5621 mlir::Location loc = getLoc();
5622 if (triples.size()) {
5623 result.assign(triples.begin(), triples.end());
5624 } else {
5625 auto one = builder.createIntegerConstant(loc, builder.getIndexType(), 1);
5626 if (!shapeVal) {
5627 TODO(loc, "shape must be recovered from box");
5628 } else if (auto shapeOp = mlir::dyn_cast_or_null<fir::ShapeOp>(
5629 shapeVal.getDefiningOp())) {
5630 for (auto ext : shapeOp.getExtents()) {
5631 result.push_back(one);
5632 result.push_back(ext);
5633 result.push_back(one);
5635 } else if (auto shapeShift = mlir::dyn_cast_or_null<fir::ShapeShiftOp>(
5636 shapeVal.getDefiningOp())) {
5637 for (auto [lb, ext] :
5638 llvm::zip(shapeShift.getOrigins(), shapeShift.getExtents())) {
5639 result.push_back(lb);
5640 result.push_back(ext);
5641 result.push_back(one);
5643 } else {
5644 TODO(loc, "shape must be recovered from box");
5647 return result;
5650 /// Base case of generating an array reference,
5651 CC genarr(const ExtValue &extMemref, ComponentPath &components,
5652 mlir::Value CrayPtr = nullptr) {
5653 mlir::Location loc = getLoc();
5654 mlir::Value memref = fir::getBase(extMemref);
5655 mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(memref.getType());
5656 assert(mlir::isa<fir::SequenceType>(arrTy) &&
5657 "memory ref must be an array");
5658 mlir::Value shape = builder.createShape(loc, extMemref);
5659 mlir::Value slice;
5660 if (components.isSlice()) {
5661 if (isBoxValue() && components.substring) {
5662 // Append the substring operator to emboxing Op as it will become an
5663 // interior adjustment (add offset, adjust LEN) to the CHARACTER value
5664 // being referenced in the descriptor.
5665 llvm::SmallVector<mlir::Value> substringBounds;
5666 populateBounds(substringBounds, components.substring);
5667 // Convert to (offset, size)
5668 mlir::Type iTy = substringBounds[0].getType();
5669 if (substringBounds.size() != 2) {
5670 fir::CharacterType charTy =
5671 fir::factory::CharacterExprHelper::getCharType(arrTy);
5672 if (charTy.hasConstantLen()) {
5673 mlir::IndexType idxTy = builder.getIndexType();
5674 fir::CharacterType::LenType charLen = charTy.getLen();
5675 mlir::Value lenValue =
5676 builder.createIntegerConstant(loc, idxTy, charLen);
5677 substringBounds.push_back(lenValue);
5678 } else {
5679 llvm::SmallVector<mlir::Value> typeparams =
5680 fir::getTypeParams(extMemref);
5681 substringBounds.push_back(typeparams.back());
5684 // Convert the lower bound to 0-based substring.
5685 mlir::Value one =
5686 builder.createIntegerConstant(loc, substringBounds[0].getType(), 1);
5687 substringBounds[0] =
5688 builder.create<mlir::arith::SubIOp>(loc, substringBounds[0], one);
5689 // Convert the upper bound to a length.
5690 mlir::Value cast = builder.createConvert(loc, iTy, substringBounds[1]);
5691 mlir::Value zero = builder.createIntegerConstant(loc, iTy, 0);
5692 auto size =
5693 builder.create<mlir::arith::SubIOp>(loc, cast, substringBounds[0]);
5694 auto cmp = builder.create<mlir::arith::CmpIOp>(
5695 loc, mlir::arith::CmpIPredicate::sgt, size, zero);
5696 // size = MAX(upper - (lower - 1), 0)
5697 substringBounds[1] =
5698 builder.create<mlir::arith::SelectOp>(loc, cmp, size, zero);
5699 slice = builder.create<fir::SliceOp>(
5700 loc, padSlice(components.trips, shape), components.suffixComponents,
5701 substringBounds);
5702 } else {
5703 slice = builder.createSlice(loc, extMemref, components.trips,
5704 components.suffixComponents);
5706 if (components.hasComponents()) {
5707 auto seqTy = mlir::cast<fir::SequenceType>(arrTy);
5708 mlir::Type eleTy =
5709 fir::applyPathToType(seqTy.getEleTy(), components.suffixComponents);
5710 if (!eleTy)
5711 fir::emitFatalError(loc, "slicing path is ill-formed");
5712 if (auto realTy = mlir::dyn_cast<fir::RealType>(eleTy))
5713 eleTy = Fortran::lower::convertReal(realTy.getContext(),
5714 realTy.getFKind());
5716 // create the type of the projected array.
5717 arrTy = fir::SequenceType::get(seqTy.getShape(), eleTy);
5718 LLVM_DEBUG(llvm::dbgs()
5719 << "type of array projection from component slicing: "
5720 << eleTy << ", " << arrTy << '\n');
5723 arrayOperands.push_back(ArrayOperand{memref, shape, slice});
5724 if (destShape.empty())
5725 destShape = getShape(arrayOperands.back());
5726 if (isBoxValue()) {
5727 // Semantics are a reference to a boxed array.
5728 // This case just requires that an embox operation be created to box the
5729 // value. The value of the box is forwarded in the continuation.
5730 mlir::Type reduceTy = reduceRank(arrTy, slice);
5731 mlir::Type boxTy = fir::BoxType::get(reduceTy);
5732 if (mlir::isa<fir::ClassType>(memref.getType()) &&
5733 !components.hasComponents())
5734 boxTy = fir::ClassType::get(reduceTy);
5735 if (components.substring) {
5736 // Adjust char length to substring size.
5737 fir::CharacterType charTy =
5738 fir::factory::CharacterExprHelper::getCharType(reduceTy);
5739 auto seqTy = mlir::cast<fir::SequenceType>(reduceTy);
5740 // TODO: Use a constant for fir.char LEN if we can compute it.
5741 boxTy = fir::BoxType::get(
5742 fir::SequenceType::get(fir::CharacterType::getUnknownLen(
5743 builder.getContext(), charTy.getFKind()),
5744 seqTy.getDimension()));
5746 llvm::SmallVector<mlir::Value> lbounds;
5747 llvm::SmallVector<mlir::Value> nonDeferredLenParams;
5748 if (!slice) {
5749 lbounds =
5750 fir::factory::getNonDefaultLowerBounds(builder, loc, extMemref);
5751 nonDeferredLenParams = fir::factory::getNonDeferredLenParams(extMemref);
5753 mlir::Value embox =
5754 mlir::isa<fir::BaseBoxType>(memref.getType())
5755 ? builder.create<fir::ReboxOp>(loc, boxTy, memref, shape, slice)
5756 .getResult()
5757 : builder
5758 .create<fir::EmboxOp>(loc, boxTy, memref, shape, slice,
5759 fir::getTypeParams(extMemref))
5760 .getResult();
5761 return [=](IterSpace) -> ExtValue {
5762 return fir::BoxValue(embox, lbounds, nonDeferredLenParams);
5765 auto eleTy = mlir::cast<fir::SequenceType>(arrTy).getEleTy();
5766 if (isReferentiallyOpaque()) {
5767 // Semantics are an opaque reference to an array.
5768 // This case forwards a continuation that will generate the address
5769 // arithmetic to the array element. This does not have copy-in/copy-out
5770 // semantics. No attempt to copy the array value will be made during the
5771 // interpretation of the Fortran statement.
5772 mlir::Type refEleTy = builder.getRefType(eleTy);
5773 return [=](IterSpace iters) -> ExtValue {
5774 // ArrayCoorOp does not expect zero based indices.
5775 llvm::SmallVector<mlir::Value> indices = fir::factory::originateIndices(
5776 loc, builder, memref.getType(), shape, iters.iterVec());
5777 mlir::Value coor = builder.create<fir::ArrayCoorOp>(
5778 loc, refEleTy, memref, shape, slice, indices,
5779 fir::getTypeParams(extMemref));
5780 if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
5781 llvm::SmallVector<mlir::Value> substringBounds;
5782 populateBounds(substringBounds, components.substring);
5783 if (!substringBounds.empty()) {
5784 mlir::Value dstLen = fir::factory::genLenOfCharacter(
5785 builder, loc, mlir::cast<fir::SequenceType>(arrTy), memref,
5786 fir::getTypeParams(extMemref), iters.iterVec(),
5787 substringBounds);
5788 fir::CharBoxValue dstChar(coor, dstLen);
5789 return fir::factory::CharacterExprHelper{builder, loc}
5790 .createSubstring(dstChar, substringBounds);
5793 return fir::factory::arraySectionElementToExtendedValue(
5794 builder, loc, extMemref, coor, slice);
5797 auto arrLoad = builder.create<fir::ArrayLoadOp>(
5798 loc, arrTy, memref, shape, slice, fir::getTypeParams(extMemref));
5800 if (CrayPtr) {
5801 mlir::Type ptrTy = CrayPtr.getType();
5802 mlir::Value cnvrt = Fortran::lower::addCrayPointerInst(
5803 loc, builder, CrayPtr, ptrTy, memref.getType());
5804 auto addr = builder.create<fir::LoadOp>(loc, cnvrt);
5805 arrLoad = builder.create<fir::ArrayLoadOp>(loc, arrTy, addr, shape, slice,
5806 fir::getTypeParams(extMemref));
5809 mlir::Value arrLd = arrLoad.getResult();
5810 if (isProjectedCopyInCopyOut()) {
5811 // Semantics are projected copy-in copy-out.
5812 // The backing store of the destination of an array expression may be
5813 // partially modified. These updates are recorded in FIR by forwarding a
5814 // continuation that generates an `array_update` Op. The destination is
5815 // always loaded at the beginning of the statement and merged at the
5816 // end.
5817 destination = arrLoad;
5818 auto lambda = ccStoreToDest
5819 ? *ccStoreToDest
5820 : defaultStoreToDestination(components.substring);
5821 return [=](IterSpace iters) -> ExtValue { return lambda(iters); };
5823 if (isCustomCopyInCopyOut()) {
5824 // Create an array_modify to get the LHS element address and indicate
5825 // the assignment, the actual assignment must be implemented in
5826 // ccStoreToDest.
5827 destination = arrLoad;
5828 return [=](IterSpace iters) -> ExtValue {
5829 mlir::Value innerArg = iters.innerArgument();
5830 mlir::Type resTy = innerArg.getType();
5831 mlir::Type eleTy = fir::applyPathToType(resTy, iters.iterVec());
5832 mlir::Type refEleTy =
5833 fir::isa_ref_type(eleTy) ? eleTy : builder.getRefType(eleTy);
5834 auto arrModify = builder.create<fir::ArrayModifyOp>(
5835 loc, mlir::TypeRange{refEleTy, resTy}, innerArg, iters.iterVec(),
5836 destination.getTypeparams());
5837 return abstractArrayExtValue(arrModify.getResult(1));
5840 if (isCopyInCopyOut()) {
5841 // Semantics are copy-in copy-out.
5842 // The continuation simply forwards the result of the `array_load` Op,
5843 // which is the value of the array as it was when loaded. All data
5844 // references with rank > 0 in an array expression typically have
5845 // copy-in copy-out semantics.
5846 return [=](IterSpace) -> ExtValue { return arrLd; };
5848 llvm::SmallVector<mlir::Value> arrLdTypeParams =
5849 fir::factory::getTypeParams(loc, builder, arrLoad);
5850 if (isValueAttribute()) {
5851 // Semantics are value attribute.
5852 // Here the continuation will `array_fetch` a value from an array and
5853 // then store that value in a temporary. One can thus imitate pass by
5854 // value even when the call is pass by reference.
5855 return [=](IterSpace iters) -> ExtValue {
5856 mlir::Value base;
5857 mlir::Type eleTy = fir::applyPathToType(arrTy, iters.iterVec());
5858 if (isAdjustedArrayElementType(eleTy)) {
5859 mlir::Type eleRefTy = builder.getRefType(eleTy);
5860 base = builder.create<fir::ArrayAccessOp>(
5861 loc, eleRefTy, arrLd, iters.iterVec(), arrLdTypeParams);
5862 } else {
5863 base = builder.create<fir::ArrayFetchOp>(
5864 loc, eleTy, arrLd, iters.iterVec(), arrLdTypeParams);
5866 mlir::Value temp =
5867 builder.createTemporary(loc, base.getType(),
5868 llvm::ArrayRef<mlir::NamedAttribute>{
5869 fir::getAdaptToByRefAttr(builder)});
5870 builder.create<fir::StoreOp>(loc, base, temp);
5871 return fir::factory::arraySectionElementToExtendedValue(
5872 builder, loc, extMemref, temp, slice);
5875 // In the default case, the array reference forwards an `array_fetch` or
5876 // `array_access` Op in the continuation.
5877 return [=](IterSpace iters) -> ExtValue {
5878 mlir::Type eleTy = fir::applyPathToType(arrTy, iters.iterVec());
5879 if (isAdjustedArrayElementType(eleTy)) {
5880 mlir::Type eleRefTy = builder.getRefType(eleTy);
5881 mlir::Value arrayOp = builder.create<fir::ArrayAccessOp>(
5882 loc, eleRefTy, arrLd, iters.iterVec(), arrLdTypeParams);
5883 if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
5884 llvm::SmallVector<mlir::Value> substringBounds;
5885 populateBounds(substringBounds, components.substring);
5886 if (!substringBounds.empty()) {
5887 mlir::Value dstLen = fir::factory::genLenOfCharacter(
5888 builder, loc, arrLoad, iters.iterVec(), substringBounds);
5889 fir::CharBoxValue dstChar(arrayOp, dstLen);
5890 return fir::factory::CharacterExprHelper{builder, loc}
5891 .createSubstring(dstChar, substringBounds);
5894 return fir::factory::arraySectionElementToExtendedValue(
5895 builder, loc, extMemref, arrayOp, slice);
5897 auto arrFetch = builder.create<fir::ArrayFetchOp>(
5898 loc, eleTy, arrLd, iters.iterVec(), arrLdTypeParams);
5899 return fir::factory::arraySectionElementToExtendedValue(
5900 builder, loc, extMemref, arrFetch, slice);
5904 std::tuple<CC, mlir::Value, mlir::Type>
5905 genOptionalArrayFetch(const Fortran::lower::SomeExpr &expr) {
5906 assert(expr.Rank() > 0 && "expr must be an array");
5907 mlir::Location loc = getLoc();
5908 ExtValue optionalArg = asInquired(expr);
5909 mlir::Value isPresent = genActualIsPresentTest(builder, loc, optionalArg);
5910 // Generate an array load and access to an array that may be an absent
5911 // optional or an unallocated optional.
5912 mlir::Value base = getBase(optionalArg);
5913 const bool hasOptionalAttr =
5914 fir::valueHasFirAttribute(base, fir::getOptionalAttrName());
5915 mlir::Type baseType = fir::unwrapRefType(base.getType());
5916 const bool isBox = mlir::isa<fir::BoxType>(baseType);
5917 const bool isAllocOrPtr =
5918 Fortran::evaluate::IsAllocatableOrPointerObject(expr);
5919 mlir::Type arrType = fir::unwrapPassByRefType(baseType);
5920 mlir::Type eleType = fir::unwrapSequenceType(arrType);
5921 ExtValue exv = optionalArg;
5922 if (hasOptionalAttr && isBox && !isAllocOrPtr) {
5923 // Elemental argument cannot be allocatable or pointers (C15100).
5924 // Hence, per 15.5.2.12 3 (8) and (9), the provided Allocatable and
5925 // Pointer optional arrays cannot be absent. The only kind of entities
5926 // that can get here are optional assumed shape and polymorphic entities.
5927 exv = absentBoxToUnallocatedBox(builder, loc, exv, isPresent);
5929 // All the properties can be read from any fir.box but the read values may
5930 // be undefined and should only be used inside a fir.if (canBeRead) region.
5931 if (const auto *mutableBox = exv.getBoxOf<fir::MutableBoxValue>())
5932 exv = fir::factory::genMutableBoxRead(builder, loc, *mutableBox);
5934 mlir::Value memref = fir::getBase(exv);
5935 mlir::Value shape = builder.createShape(loc, exv);
5936 mlir::Value noSlice;
5937 auto arrLoad = builder.create<fir::ArrayLoadOp>(
5938 loc, arrType, memref, shape, noSlice, fir::getTypeParams(exv));
5939 mlir::Operation::operand_range arrLdTypeParams = arrLoad.getTypeparams();
5940 mlir::Value arrLd = arrLoad.getResult();
5941 // Mark the load to tell later passes it is unsafe to use this array_load
5942 // shape unconditionally.
5943 arrLoad->setAttr(fir::getOptionalAttrName(), builder.getUnitAttr());
5945 // Place the array as optional on the arrayOperands stack so that its
5946 // shape will only be used as a fallback to induce the implicit loop nest
5947 // (that is if there is no non optional array arguments).
5948 arrayOperands.push_back(
5949 ArrayOperand{memref, shape, noSlice, /*mayBeAbsent=*/true});
5951 // By value semantics.
5952 auto cc = [=](IterSpace iters) -> ExtValue {
5953 auto arrFetch = builder.create<fir::ArrayFetchOp>(
5954 loc, eleType, arrLd, iters.iterVec(), arrLdTypeParams);
5955 return fir::factory::arraySectionElementToExtendedValue(
5956 builder, loc, exv, arrFetch, noSlice);
5958 return {cc, isPresent, eleType};
5961 /// Generate a continuation to pass \p expr to an OPTIONAL argument of an
5962 /// elemental procedure. This is meant to handle the cases where \p expr might
5963 /// be dynamically absent (i.e. when it is a POINTER, an ALLOCATABLE or an
5964 /// OPTIONAL variable). If p\ expr is guaranteed to be present genarr() can
5965 /// directly be called instead.
5966 CC genarrForwardOptionalArgumentToCall(const Fortran::lower::SomeExpr &expr) {
5967 mlir::Location loc = getLoc();
5968 // Only by-value numerical and logical so far.
5969 if (semant != ConstituentSemantics::RefTransparent)
5970 TODO(loc, "optional arguments in user defined elemental procedures");
5972 // Handle scalar argument case (the if-then-else is generated outside of the
5973 // implicit loop nest).
5974 if (expr.Rank() == 0) {
5975 ExtValue optionalArg = asInquired(expr);
5976 mlir::Value isPresent = genActualIsPresentTest(builder, loc, optionalArg);
5977 mlir::Value elementValue =
5978 fir::getBase(genOptionalValue(builder, loc, optionalArg, isPresent));
5979 return [=](IterSpace iters) -> ExtValue { return elementValue; };
5982 CC cc;
5983 mlir::Value isPresent;
5984 mlir::Type eleType;
5985 std::tie(cc, isPresent, eleType) = genOptionalArrayFetch(expr);
5986 return [=](IterSpace iters) -> ExtValue {
5987 mlir::Value elementValue =
5988 builder
5989 .genIfOp(loc, {eleType}, isPresent,
5990 /*withElseRegion=*/true)
5991 .genThen([&]() {
5992 builder.create<fir::ResultOp>(loc, fir::getBase(cc(iters)));
5994 .genElse([&]() {
5995 mlir::Value zero =
5996 fir::factory::createZeroValue(builder, loc, eleType);
5997 builder.create<fir::ResultOp>(loc, zero);
5999 .getResults()[0];
6000 return elementValue;
6004 /// Reduce the rank of a array to be boxed based on the slice's operands.
6005 static mlir::Type reduceRank(mlir::Type arrTy, mlir::Value slice) {
6006 if (slice) {
6007 auto slOp = mlir::dyn_cast<fir::SliceOp>(slice.getDefiningOp());
6008 assert(slOp && "expected slice op");
6009 auto seqTy = mlir::dyn_cast<fir::SequenceType>(arrTy);
6010 assert(seqTy && "expected array type");
6011 mlir::Operation::operand_range triples = slOp.getTriples();
6012 fir::SequenceType::Shape shape;
6013 // reduce the rank for each invariant dimension
6014 for (unsigned i = 1, end = triples.size(); i < end; i += 3) {
6015 if (auto extent = fir::factory::getExtentFromTriplet(
6016 triples[i - 1], triples[i], triples[i + 1]))
6017 shape.push_back(*extent);
6018 else if (!mlir::isa_and_nonnull<fir::UndefOp>(
6019 triples[i].getDefiningOp()))
6020 shape.push_back(fir::SequenceType::getUnknownExtent());
6022 return fir::SequenceType::get(shape, seqTy.getEleTy());
6024 // not sliced, so no change in rank
6025 return arrTy;
6028 /// Example: <code>array%RE</code>
6029 CC genarr(const Fortran::evaluate::ComplexPart &x,
6030 ComponentPath &components) {
6031 components.reversePath.push_back(&x);
6032 return genarr(x.complex(), components);
6035 template <typename A>
6036 CC genSlicePath(const A &x, ComponentPath &components) {
6037 return genarr(x, components);
6040 CC genarr(const Fortran::evaluate::StaticDataObject::Pointer &,
6041 ComponentPath &components) {
6042 TODO(getLoc(), "substring of static object inside FORALL");
6045 /// Substrings (see 9.4.1)
6046 CC genarr(const Fortran::evaluate::Substring &x, ComponentPath &components) {
6047 components.substring = &x;
6048 return Fortran::common::visit(
6049 [&](const auto &v) { return genarr(v, components); }, x.parent());
6052 template <typename T>
6053 CC genarr(const Fortran::evaluate::FunctionRef<T> &funRef) {
6054 // Note that it's possible that the function being called returns either an
6055 // array or a scalar. In the first case, use the element type of the array.
6056 return genProcRef(
6057 funRef, fir::unwrapSequenceType(converter.genType(toEvExpr(funRef))));
6060 //===--------------------------------------------------------------------===//
6061 // Array construction
6062 //===--------------------------------------------------------------------===//
6064 /// Target agnostic computation of the size of an element in the array.
6065 /// Returns the size in bytes with type `index` or a null Value if the element
6066 /// size is not constant.
6067 mlir::Value computeElementSize(const ExtValue &exv, mlir::Type eleTy,
6068 mlir::Type resTy) {
6069 mlir::Location loc = getLoc();
6070 mlir::IndexType idxTy = builder.getIndexType();
6071 mlir::Value multiplier = builder.createIntegerConstant(loc, idxTy, 1);
6072 if (fir::hasDynamicSize(eleTy)) {
6073 if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
6074 // Array of char with dynamic LEN parameter. Downcast to an array
6075 // of singleton char, and scale by the len type parameter from
6076 // `exv`.
6077 exv.match(
6078 [&](const fir::CharBoxValue &cb) { multiplier = cb.getLen(); },
6079 [&](const fir::CharArrayBoxValue &cb) { multiplier = cb.getLen(); },
6080 [&](const fir::BoxValue &box) {
6081 multiplier = fir::factory::CharacterExprHelper(builder, loc)
6082 .readLengthFromBox(box.getAddr());
6084 [&](const fir::MutableBoxValue &box) {
6085 multiplier = fir::factory::CharacterExprHelper(builder, loc)
6086 .readLengthFromBox(box.getAddr());
6088 [&](const auto &) {
6089 fir::emitFatalError(loc,
6090 "array constructor element has unknown size");
6092 fir::CharacterType newEleTy = fir::CharacterType::getSingleton(
6093 eleTy.getContext(), charTy.getFKind());
6094 if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(resTy)) {
6095 assert(eleTy == seqTy.getEleTy());
6096 resTy = fir::SequenceType::get(seqTy.getShape(), newEleTy);
6098 eleTy = newEleTy;
6099 } else {
6100 TODO(loc, "dynamic sized type");
6103 mlir::Type eleRefTy = builder.getRefType(eleTy);
6104 mlir::Type resRefTy = builder.getRefType(resTy);
6105 mlir::Value nullPtr = builder.createNullConstant(loc, resRefTy);
6106 auto offset = builder.create<fir::CoordinateOp>(
6107 loc, eleRefTy, nullPtr, mlir::ValueRange{multiplier});
6108 return builder.createConvert(loc, idxTy, offset);
6111 /// Get the function signature of the LLVM memcpy intrinsic.
6112 mlir::FunctionType memcpyType() {
6113 return fir::factory::getLlvmMemcpy(builder).getFunctionType();
6116 /// Create a call to the LLVM memcpy intrinsic.
6117 void createCallMemcpy(llvm::ArrayRef<mlir::Value> args) {
6118 mlir::Location loc = getLoc();
6119 mlir::func::FuncOp memcpyFunc = fir::factory::getLlvmMemcpy(builder);
6120 mlir::SymbolRefAttr funcSymAttr =
6121 builder.getSymbolRefAttr(memcpyFunc.getName());
6122 mlir::FunctionType funcTy = memcpyFunc.getFunctionType();
6123 builder.create<fir::CallOp>(loc, funcTy.getResults(), funcSymAttr, args);
6126 // Construct code to check for a buffer overrun and realloc the buffer when
6127 // space is depleted. This is done between each item in the ac-value-list.
6128 mlir::Value growBuffer(mlir::Value mem, mlir::Value needed,
6129 mlir::Value bufferSize, mlir::Value buffSize,
6130 mlir::Value eleSz) {
6131 mlir::Location loc = getLoc();
6132 mlir::func::FuncOp reallocFunc = fir::factory::getRealloc(builder);
6133 auto cond = builder.create<mlir::arith::CmpIOp>(
6134 loc, mlir::arith::CmpIPredicate::sle, bufferSize, needed);
6135 auto ifOp = builder.create<fir::IfOp>(loc, mem.getType(), cond,
6136 /*withElseRegion=*/true);
6137 auto insPt = builder.saveInsertionPoint();
6138 builder.setInsertionPointToStart(&ifOp.getThenRegion().front());
6139 // Not enough space, resize the buffer.
6140 mlir::IndexType idxTy = builder.getIndexType();
6141 mlir::Value two = builder.createIntegerConstant(loc, idxTy, 2);
6142 auto newSz = builder.create<mlir::arith::MulIOp>(loc, needed, two);
6143 builder.create<fir::StoreOp>(loc, newSz, buffSize);
6144 mlir::Value byteSz = builder.create<mlir::arith::MulIOp>(loc, newSz, eleSz);
6145 mlir::SymbolRefAttr funcSymAttr =
6146 builder.getSymbolRefAttr(reallocFunc.getName());
6147 mlir::FunctionType funcTy = reallocFunc.getFunctionType();
6148 auto newMem = builder.create<fir::CallOp>(
6149 loc, funcTy.getResults(), funcSymAttr,
6150 llvm::ArrayRef<mlir::Value>{
6151 builder.createConvert(loc, funcTy.getInputs()[0], mem),
6152 builder.createConvert(loc, funcTy.getInputs()[1], byteSz)});
6153 mlir::Value castNewMem =
6154 builder.createConvert(loc, mem.getType(), newMem.getResult(0));
6155 builder.create<fir::ResultOp>(loc, castNewMem);
6156 builder.setInsertionPointToStart(&ifOp.getElseRegion().front());
6157 // Otherwise, just forward the buffer.
6158 builder.create<fir::ResultOp>(loc, mem);
6159 builder.restoreInsertionPoint(insPt);
6160 return ifOp.getResult(0);
6163 /// Copy the next value (or vector of values) into the array being
6164 /// constructed.
6165 mlir::Value copyNextArrayCtorSection(const ExtValue &exv, mlir::Value buffPos,
6166 mlir::Value buffSize, mlir::Value mem,
6167 mlir::Value eleSz, mlir::Type eleTy,
6168 mlir::Type eleRefTy, mlir::Type resTy) {
6169 mlir::Location loc = getLoc();
6170 auto off = builder.create<fir::LoadOp>(loc, buffPos);
6171 auto limit = builder.create<fir::LoadOp>(loc, buffSize);
6172 mlir::IndexType idxTy = builder.getIndexType();
6173 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
6175 if (fir::isRecordWithAllocatableMember(eleTy))
6176 TODO(loc, "deep copy on allocatable members");
6178 if (!eleSz) {
6179 // Compute the element size at runtime.
6180 assert(fir::hasDynamicSize(eleTy));
6181 if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
6182 auto charBytes =
6183 builder.getKindMap().getCharacterBitsize(charTy.getFKind()) / 8;
6184 mlir::Value bytes =
6185 builder.createIntegerConstant(loc, idxTy, charBytes);
6186 mlir::Value length = fir::getLen(exv);
6187 if (!length)
6188 fir::emitFatalError(loc, "result is not boxed character");
6189 eleSz = builder.create<mlir::arith::MulIOp>(loc, bytes, length);
6190 } else {
6191 TODO(loc, "PDT size");
6192 // Will call the PDT's size function with the type parameters.
6196 // Compute the coordinate using `fir.coordinate_of`, or, if the type has
6197 // dynamic size, generating the pointer arithmetic.
6198 auto computeCoordinate = [&](mlir::Value buff, mlir::Value off) {
6199 mlir::Type refTy = eleRefTy;
6200 if (fir::hasDynamicSize(eleTy)) {
6201 if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
6202 // Scale a simple pointer using dynamic length and offset values.
6203 auto chTy = fir::CharacterType::getSingleton(charTy.getContext(),
6204 charTy.getFKind());
6205 refTy = builder.getRefType(chTy);
6206 mlir::Type toTy = builder.getRefType(builder.getVarLenSeqTy(chTy));
6207 buff = builder.createConvert(loc, toTy, buff);
6208 off = builder.create<mlir::arith::MulIOp>(loc, off, eleSz);
6209 } else {
6210 TODO(loc, "PDT offset");
6213 auto coor = builder.create<fir::CoordinateOp>(loc, refTy, buff,
6214 mlir::ValueRange{off});
6215 return builder.createConvert(loc, eleRefTy, coor);
6218 // Lambda to lower an abstract array box value.
6219 auto doAbstractArray = [&](const auto &v) {
6220 // Compute the array size.
6221 mlir::Value arrSz = one;
6222 for (auto ext : v.getExtents())
6223 arrSz = builder.create<mlir::arith::MulIOp>(loc, arrSz, ext);
6225 // Grow the buffer as needed.
6226 auto endOff = builder.create<mlir::arith::AddIOp>(loc, off, arrSz);
6227 mem = growBuffer(mem, endOff, limit, buffSize, eleSz);
6229 // Copy the elements to the buffer.
6230 mlir::Value byteSz =
6231 builder.create<mlir::arith::MulIOp>(loc, arrSz, eleSz);
6232 auto buff = builder.createConvert(loc, fir::HeapType::get(resTy), mem);
6233 mlir::Value buffi = computeCoordinate(buff, off);
6234 llvm::SmallVector<mlir::Value> args = fir::runtime::createArguments(
6235 builder, loc, memcpyType(), buffi, v.getAddr(), byteSz,
6236 /*volatile=*/builder.createBool(loc, false));
6237 createCallMemcpy(args);
6239 // Save the incremented buffer position.
6240 builder.create<fir::StoreOp>(loc, endOff, buffPos);
6243 // Copy a trivial scalar value into the buffer.
6244 auto doTrivialScalar = [&](const ExtValue &v, mlir::Value len = {}) {
6245 // Increment the buffer position.
6246 auto plusOne = builder.create<mlir::arith::AddIOp>(loc, off, one);
6248 // Grow the buffer as needed.
6249 mem = growBuffer(mem, plusOne, limit, buffSize, eleSz);
6251 // Store the element in the buffer.
6252 mlir::Value buff =
6253 builder.createConvert(loc, fir::HeapType::get(resTy), mem);
6254 auto buffi = builder.create<fir::CoordinateOp>(loc, eleRefTy, buff,
6255 mlir::ValueRange{off});
6256 fir::factory::genScalarAssignment(
6257 builder, loc,
6258 [&]() -> ExtValue {
6259 if (len)
6260 return fir::CharBoxValue(buffi, len);
6261 return buffi;
6262 }(),
6264 builder.create<fir::StoreOp>(loc, plusOne, buffPos);
6267 // Copy the value.
6268 exv.match(
6269 [&](mlir::Value) { doTrivialScalar(exv); },
6270 [&](const fir::CharBoxValue &v) {
6271 auto buffer = v.getBuffer();
6272 if (fir::isa_char(buffer.getType())) {
6273 doTrivialScalar(exv, eleSz);
6274 } else {
6275 // Increment the buffer position.
6276 auto plusOne = builder.create<mlir::arith::AddIOp>(loc, off, one);
6278 // Grow the buffer as needed.
6279 mem = growBuffer(mem, plusOne, limit, buffSize, eleSz);
6281 // Store the element in the buffer.
6282 mlir::Value buff =
6283 builder.createConvert(loc, fir::HeapType::get(resTy), mem);
6284 mlir::Value buffi = computeCoordinate(buff, off);
6285 llvm::SmallVector<mlir::Value> args = fir::runtime::createArguments(
6286 builder, loc, memcpyType(), buffi, v.getAddr(), eleSz,
6287 /*volatile=*/builder.createBool(loc, false));
6288 createCallMemcpy(args);
6290 builder.create<fir::StoreOp>(loc, plusOne, buffPos);
6293 [&](const fir::ArrayBoxValue &v) { doAbstractArray(v); },
6294 [&](const fir::CharArrayBoxValue &v) { doAbstractArray(v); },
6295 [&](const auto &) {
6296 TODO(loc, "unhandled array constructor expression");
6298 return mem;
6301 // Lower the expr cases in an ac-value-list.
6302 template <typename A>
6303 std::pair<ExtValue, bool>
6304 genArrayCtorInitializer(const Fortran::evaluate::Expr<A> &x, mlir::Type,
6305 mlir::Value, mlir::Value, mlir::Value,
6306 Fortran::lower::StatementContext &stmtCtx) {
6307 if (isArray(x))
6308 return {lowerNewArrayExpression(converter, symMap, stmtCtx, toEvExpr(x)),
6309 /*needCopy=*/true};
6310 return {asScalar(x), /*needCopy=*/true};
6313 // Lower an ac-implied-do in an ac-value-list.
6314 template <typename A>
6315 std::pair<ExtValue, bool>
6316 genArrayCtorInitializer(const Fortran::evaluate::ImpliedDo<A> &x,
6317 mlir::Type resTy, mlir::Value mem,
6318 mlir::Value buffPos, mlir::Value buffSize,
6319 Fortran::lower::StatementContext &) {
6320 mlir::Location loc = getLoc();
6321 mlir::IndexType idxTy = builder.getIndexType();
6322 mlir::Value lo =
6323 builder.createConvert(loc, idxTy, fir::getBase(asScalar(x.lower())));
6324 mlir::Value up =
6325 builder.createConvert(loc, idxTy, fir::getBase(asScalar(x.upper())));
6326 mlir::Value step =
6327 builder.createConvert(loc, idxTy, fir::getBase(asScalar(x.stride())));
6328 auto seqTy = mlir::cast<fir::SequenceType>(resTy);
6329 mlir::Type eleTy = fir::unwrapSequenceType(seqTy);
6330 auto loop =
6331 builder.create<fir::DoLoopOp>(loc, lo, up, step, /*unordered=*/false,
6332 /*finalCount=*/false, mem);
6333 // create a new binding for x.name(), to ac-do-variable, to the iteration
6334 // value.
6335 symMap.pushImpliedDoBinding(toStringRef(x.name()), loop.getInductionVar());
6336 auto insPt = builder.saveInsertionPoint();
6337 builder.setInsertionPointToStart(loop.getBody());
6338 // Thread mem inside the loop via loop argument.
6339 mem = loop.getRegionIterArgs()[0];
6341 mlir::Type eleRefTy = builder.getRefType(eleTy);
6343 // Any temps created in the loop body must be freed inside the loop body.
6344 stmtCtx.pushScope();
6345 std::optional<mlir::Value> charLen;
6346 for (const Fortran::evaluate::ArrayConstructorValue<A> &acv : x.values()) {
6347 auto [exv, copyNeeded] = Fortran::common::visit(
6348 [&](const auto &v) {
6349 return genArrayCtorInitializer(v, resTy, mem, buffPos, buffSize,
6350 stmtCtx);
6352 acv.u);
6353 mlir::Value eleSz = computeElementSize(exv, eleTy, resTy);
6354 mem = copyNeeded ? copyNextArrayCtorSection(exv, buffPos, buffSize, mem,
6355 eleSz, eleTy, eleRefTy, resTy)
6356 : fir::getBase(exv);
6357 if (fir::isa_char(seqTy.getEleTy()) && !charLen) {
6358 charLen = builder.createTemporary(loc, builder.getI64Type());
6359 mlir::Value castLen =
6360 builder.createConvert(loc, builder.getI64Type(), fir::getLen(exv));
6361 assert(charLen.has_value());
6362 builder.create<fir::StoreOp>(loc, castLen, *charLen);
6365 stmtCtx.finalizeAndPop();
6367 builder.create<fir::ResultOp>(loc, mem);
6368 builder.restoreInsertionPoint(insPt);
6369 mem = loop.getResult(0);
6370 symMap.popImpliedDoBinding();
6371 llvm::SmallVector<mlir::Value> extents = {
6372 builder.create<fir::LoadOp>(loc, buffPos).getResult()};
6374 // Convert to extended value.
6375 if (fir::isa_char(seqTy.getEleTy())) {
6376 assert(charLen.has_value());
6377 auto len = builder.create<fir::LoadOp>(loc, *charLen);
6378 return {fir::CharArrayBoxValue{mem, len, extents}, /*needCopy=*/false};
6380 return {fir::ArrayBoxValue{mem, extents}, /*needCopy=*/false};
6383 // To simplify the handling and interaction between the various cases, array
6384 // constructors are always lowered to the incremental construction code
6385 // pattern, even if the extent of the array value is constant. After the
6386 // MemToReg pass and constant folding, the optimizer should be able to
6387 // determine that all the buffer overrun tests are false when the
6388 // incremental construction wasn't actually required.
6389 template <typename A>
6390 CC genarr(const Fortran::evaluate::ArrayConstructor<A> &x) {
6391 mlir::Location loc = getLoc();
6392 auto evExpr = toEvExpr(x);
6393 mlir::Type resTy = translateSomeExprToFIRType(converter, evExpr);
6394 mlir::IndexType idxTy = builder.getIndexType();
6395 auto seqTy = mlir::cast<fir::SequenceType>(resTy);
6396 mlir::Type eleTy = fir::unwrapSequenceType(resTy);
6397 mlir::Value buffSize = builder.createTemporary(loc, idxTy, ".buff.size");
6398 mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0);
6399 mlir::Value buffPos = builder.createTemporary(loc, idxTy, ".buff.pos");
6400 builder.create<fir::StoreOp>(loc, zero, buffPos);
6401 // Allocate space for the array to be constructed.
6402 mlir::Value mem;
6403 if (fir::hasDynamicSize(resTy)) {
6404 if (fir::hasDynamicSize(eleTy)) {
6405 // The size of each element may depend on a general expression. Defer
6406 // creating the buffer until after the expression is evaluated.
6407 mem = builder.createNullConstant(loc, builder.getRefType(eleTy));
6408 builder.create<fir::StoreOp>(loc, zero, buffSize);
6409 } else {
6410 mlir::Value initBuffSz =
6411 builder.createIntegerConstant(loc, idxTy, clInitialBufferSize);
6412 mem = builder.create<fir::AllocMemOp>(
6413 loc, eleTy, /*typeparams=*/std::nullopt, initBuffSz);
6414 builder.create<fir::StoreOp>(loc, initBuffSz, buffSize);
6416 } else {
6417 mem = builder.create<fir::AllocMemOp>(loc, resTy);
6418 int64_t buffSz = 1;
6419 for (auto extent : seqTy.getShape())
6420 buffSz *= extent;
6421 mlir::Value initBuffSz =
6422 builder.createIntegerConstant(loc, idxTy, buffSz);
6423 builder.create<fir::StoreOp>(loc, initBuffSz, buffSize);
6425 // Compute size of element
6426 mlir::Type eleRefTy = builder.getRefType(eleTy);
6428 // Populate the buffer with the elements, growing as necessary.
6429 std::optional<mlir::Value> charLen;
6430 for (const auto &expr : x) {
6431 auto [exv, copyNeeded] = Fortran::common::visit(
6432 [&](const auto &e) {
6433 return genArrayCtorInitializer(e, resTy, mem, buffPos, buffSize,
6434 stmtCtx);
6436 expr.u);
6437 mlir::Value eleSz = computeElementSize(exv, eleTy, resTy);
6438 mem = copyNeeded ? copyNextArrayCtorSection(exv, buffPos, buffSize, mem,
6439 eleSz, eleTy, eleRefTy, resTy)
6440 : fir::getBase(exv);
6441 if (fir::isa_char(seqTy.getEleTy()) && !charLen) {
6442 charLen = builder.createTemporary(loc, builder.getI64Type());
6443 mlir::Value castLen =
6444 builder.createConvert(loc, builder.getI64Type(), fir::getLen(exv));
6445 builder.create<fir::StoreOp>(loc, castLen, *charLen);
6448 mem = builder.createConvert(loc, fir::HeapType::get(resTy), mem);
6449 llvm::SmallVector<mlir::Value> extents = {
6450 builder.create<fir::LoadOp>(loc, buffPos)};
6452 // Cleanup the temporary.
6453 fir::FirOpBuilder *bldr = &converter.getFirOpBuilder();
6454 stmtCtx.attachCleanup(
6455 [bldr, loc, mem]() { bldr->create<fir::FreeMemOp>(loc, mem); });
6457 // Return the continuation.
6458 if (fir::isa_char(seqTy.getEleTy())) {
6459 if (charLen) {
6460 auto len = builder.create<fir::LoadOp>(loc, *charLen);
6461 return genarr(fir::CharArrayBoxValue{mem, len, extents});
6463 return genarr(fir::CharArrayBoxValue{mem, zero, extents});
6465 return genarr(fir::ArrayBoxValue{mem, extents});
6468 CC genarr(const Fortran::evaluate::ImpliedDoIndex &) {
6469 fir::emitFatalError(getLoc(), "implied do index cannot have rank > 0");
6471 CC genarr(const Fortran::evaluate::TypeParamInquiry &x) {
6472 TODO(getLoc(), "array expr type parameter inquiry");
6473 return [](IterSpace iters) -> ExtValue { return mlir::Value{}; };
6475 CC genarr(const Fortran::evaluate::DescriptorInquiry &x) {
6476 TODO(getLoc(), "array expr descriptor inquiry");
6477 return [](IterSpace iters) -> ExtValue { return mlir::Value{}; };
6479 CC genarr(const Fortran::evaluate::StructureConstructor &x) {
6480 TODO(getLoc(), "structure constructor");
6481 return [](IterSpace iters) -> ExtValue { return mlir::Value{}; };
6484 //===--------------------------------------------------------------------===//
6485 // LOCICAL operators (.NOT., .AND., .EQV., etc.)
6486 //===--------------------------------------------------------------------===//
6488 template <int KIND>
6489 CC genarr(const Fortran::evaluate::Not<KIND> &x) {
6490 mlir::Location loc = getLoc();
6491 mlir::IntegerType i1Ty = builder.getI1Type();
6492 auto lambda = genarr(x.left());
6493 mlir::Value truth = builder.createBool(loc, true);
6494 return [=](IterSpace iters) -> ExtValue {
6495 mlir::Value logical = fir::getBase(lambda(iters));
6496 mlir::Value val = builder.createConvert(loc, i1Ty, logical);
6497 return builder.create<mlir::arith::XOrIOp>(loc, val, truth);
6500 template <typename OP, typename A>
6501 CC createBinaryBoolOp(const A &x) {
6502 mlir::Location loc = getLoc();
6503 mlir::IntegerType i1Ty = builder.getI1Type();
6504 auto lf = genarr(x.left());
6505 auto rf = genarr(x.right());
6506 return [=](IterSpace iters) -> ExtValue {
6507 mlir::Value left = fir::getBase(lf(iters));
6508 mlir::Value right = fir::getBase(rf(iters));
6509 mlir::Value lhs = builder.createConvert(loc, i1Ty, left);
6510 mlir::Value rhs = builder.createConvert(loc, i1Ty, right);
6511 return builder.create<OP>(loc, lhs, rhs);
6514 template <typename OP, typename A>
6515 CC createCompareBoolOp(mlir::arith::CmpIPredicate pred, const A &x) {
6516 mlir::Location loc = getLoc();
6517 mlir::IntegerType i1Ty = builder.getI1Type();
6518 auto lf = genarr(x.left());
6519 auto rf = genarr(x.right());
6520 return [=](IterSpace iters) -> ExtValue {
6521 mlir::Value left = fir::getBase(lf(iters));
6522 mlir::Value right = fir::getBase(rf(iters));
6523 mlir::Value lhs = builder.createConvert(loc, i1Ty, left);
6524 mlir::Value rhs = builder.createConvert(loc, i1Ty, right);
6525 return builder.create<OP>(loc, pred, lhs, rhs);
6528 template <int KIND>
6529 CC genarr(const Fortran::evaluate::LogicalOperation<KIND> &x) {
6530 switch (x.logicalOperator) {
6531 case Fortran::evaluate::LogicalOperator::And:
6532 return createBinaryBoolOp<mlir::arith::AndIOp>(x);
6533 case Fortran::evaluate::LogicalOperator::Or:
6534 return createBinaryBoolOp<mlir::arith::OrIOp>(x);
6535 case Fortran::evaluate::LogicalOperator::Eqv:
6536 return createCompareBoolOp<mlir::arith::CmpIOp>(
6537 mlir::arith::CmpIPredicate::eq, x);
6538 case Fortran::evaluate::LogicalOperator::Neqv:
6539 return createCompareBoolOp<mlir::arith::CmpIOp>(
6540 mlir::arith::CmpIPredicate::ne, x);
6541 case Fortran::evaluate::LogicalOperator::Not:
6542 llvm_unreachable(".NOT. handled elsewhere");
6544 llvm_unreachable("unhandled case");
6547 //===--------------------------------------------------------------------===//
6548 // Relational operators (<, <=, ==, etc.)
6549 //===--------------------------------------------------------------------===//
6551 template <typename OP, typename PRED, typename A>
6552 CC createCompareOp(PRED pred, const A &x) {
6553 mlir::Location loc = getLoc();
6554 auto lf = genarr(x.left());
6555 auto rf = genarr(x.right());
6556 return [=](IterSpace iters) -> ExtValue {
6557 mlir::Value lhs = fir::getBase(lf(iters));
6558 mlir::Value rhs = fir::getBase(rf(iters));
6559 return builder.create<OP>(loc, pred, lhs, rhs);
6562 template <typename A>
6563 CC createCompareCharOp(mlir::arith::CmpIPredicate pred, const A &x) {
6564 mlir::Location loc = getLoc();
6565 auto lf = genarr(x.left());
6566 auto rf = genarr(x.right());
6567 return [=](IterSpace iters) -> ExtValue {
6568 auto lhs = lf(iters);
6569 auto rhs = rf(iters);
6570 return fir::runtime::genCharCompare(builder, loc, pred, lhs, rhs);
6573 template <int KIND>
6574 CC genarr(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
6575 Fortran::common::TypeCategory::Integer, KIND>> &x) {
6576 return createCompareOp<mlir::arith::CmpIOp>(translateRelational(x.opr), x);
6578 template <int KIND>
6579 CC genarr(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
6580 Fortran::common::TypeCategory::Character, KIND>> &x) {
6581 return createCompareCharOp(translateRelational(x.opr), x);
6583 template <int KIND>
6584 CC genarr(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
6585 Fortran::common::TypeCategory::Real, KIND>> &x) {
6586 return createCompareOp<mlir::arith::CmpFOp>(translateFloatRelational(x.opr),
6589 template <int KIND>
6590 CC genarr(const Fortran::evaluate::Relational<Fortran::evaluate::Type<
6591 Fortran::common::TypeCategory::Complex, KIND>> &x) {
6592 return createCompareOp<fir::CmpcOp>(translateFloatRelational(x.opr), x);
6594 CC genarr(
6595 const Fortran::evaluate::Relational<Fortran::evaluate::SomeType> &r) {
6596 return Fortran::common::visit([&](const auto &x) { return genarr(x); },
6597 r.u);
6600 template <typename A>
6601 CC genarr(const Fortran::evaluate::Designator<A> &des) {
6602 ComponentPath components(des.Rank() > 0);
6603 return Fortran::common::visit(
6604 [&](const auto &x) { return genarr(x, components); }, des.u);
6607 /// Is the path component rank > 0?
6608 static bool ranked(const PathComponent &x) {
6609 return Fortran::common::visit(
6610 Fortran::common::visitors{
6611 [](const ImplicitSubscripts &) { return false; },
6612 [](const auto *v) { return v->Rank() > 0; }},
6616 void extendComponent(Fortran::lower::ComponentPath &component,
6617 mlir::Type coorTy, mlir::ValueRange vals) {
6618 auto *bldr = &converter.getFirOpBuilder();
6619 llvm::SmallVector<mlir::Value> offsets(vals.begin(), vals.end());
6620 auto currentFunc = component.getExtendCoorRef();
6621 auto loc = getLoc();
6622 auto newCoorRef = [bldr, coorTy, offsets, currentFunc,
6623 loc](mlir::Value val) -> mlir::Value {
6624 return bldr->create<fir::CoordinateOp>(loc, bldr->getRefType(coorTy),
6625 currentFunc(val), offsets);
6627 component.extendCoorRef = newCoorRef;
6630 //===-------------------------------------------------------------------===//
6631 // Array data references in an explicit iteration space.
6633 // Use the base array that was loaded before the loop nest.
6634 //===-------------------------------------------------------------------===//
6636 /// Lower the path (`revPath`, in reverse) to be appended to an array_fetch or
6637 /// array_update op. \p ty is the initial type of the array
6638 /// (reference). Returns the type of the element after application of the
6639 /// path in \p components.
6641 /// TODO: This needs to deal with array's with initial bounds other than 1.
6642 /// TODO: Thread type parameters correctly.
6643 mlir::Type lowerPath(const ExtValue &arrayExv, ComponentPath &components) {
6644 mlir::Location loc = getLoc();
6645 mlir::Type ty = fir::getBase(arrayExv).getType();
6646 auto &revPath = components.reversePath;
6647 ty = fir::unwrapPassByRefType(ty);
6648 bool prefix = true;
6649 bool deref = false;
6650 auto addComponentList = [&](mlir::Type ty, mlir::ValueRange vals) {
6651 if (deref) {
6652 extendComponent(components, ty, vals);
6653 } else if (prefix) {
6654 for (auto v : vals)
6655 components.prefixComponents.push_back(v);
6656 } else {
6657 for (auto v : vals)
6658 components.suffixComponents.push_back(v);
6661 mlir::IndexType idxTy = builder.getIndexType();
6662 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
6663 bool atBase = true;
6664 PushSemantics(isProjectedCopyInCopyOut()
6665 ? ConstituentSemantics::RefTransparent
6666 : nextPathSemantics());
6667 unsigned index = 0;
6668 for (const auto &v : llvm::reverse(revPath)) {
6669 Fortran::common::visit(
6670 Fortran::common::visitors{
6671 [&](const ImplicitSubscripts &) {
6672 prefix = false;
6673 ty = fir::unwrapSequenceType(ty);
6675 [&](const Fortran::evaluate::ComplexPart *x) {
6676 assert(!prefix && "complex part must be at end");
6677 mlir::Value offset = builder.createIntegerConstant(
6678 loc, builder.getI32Type(),
6679 x->part() == Fortran::evaluate::ComplexPart::Part::RE ? 0
6680 : 1);
6681 components.suffixComponents.push_back(offset);
6682 ty = fir::applyPathToType(ty, mlir::ValueRange{offset});
6684 [&](const Fortran::evaluate::ArrayRef *x) {
6685 if (Fortran::lower::isRankedArrayAccess(*x)) {
6686 genSliceIndices(components, arrayExv, *x, atBase);
6687 ty = fir::unwrapSeqOrBoxedSeqType(ty);
6688 } else {
6689 // Array access where the expressions are scalar and cannot
6690 // depend upon the implied iteration space.
6691 unsigned ssIndex = 0u;
6692 llvm::SmallVector<mlir::Value> componentsToAdd;
6693 for (const auto &ss : x->subscript()) {
6694 Fortran::common::visit(
6695 Fortran::common::visitors{
6696 [&](const Fortran::evaluate::
6697 IndirectSubscriptIntegerExpr &ie) {
6698 const auto &e = ie.value();
6699 if (isArray(e))
6700 fir::emitFatalError(
6701 loc,
6702 "multiple components along single path "
6703 "generating array subexpressions");
6704 // Lower scalar index expression, append it to
6705 // subs.
6706 mlir::Value subscriptVal =
6707 fir::getBase(asScalarArray(e));
6708 // arrayExv is the base array. It needs to reflect
6709 // the current array component instead.
6710 // FIXME: must use lower bound of this component,
6711 // not just the constant 1.
6712 mlir::Value lb =
6713 atBase ? fir::factory::readLowerBound(
6714 builder, loc, arrayExv, ssIndex,
6715 one)
6716 : one;
6717 mlir::Value val = builder.createConvert(
6718 loc, idxTy, subscriptVal);
6719 mlir::Value ivAdj =
6720 builder.create<mlir::arith::SubIOp>(
6721 loc, idxTy, val, lb);
6722 componentsToAdd.push_back(
6723 builder.createConvert(loc, idxTy, ivAdj));
6725 [&](const auto &) {
6726 fir::emitFatalError(
6727 loc, "multiple components along single path "
6728 "generating array subexpressions");
6730 ss.u);
6731 ssIndex++;
6733 ty = fir::unwrapSeqOrBoxedSeqType(ty);
6734 addComponentList(ty, componentsToAdd);
6737 [&](const Fortran::evaluate::Component *x) {
6738 auto fieldTy = fir::FieldType::get(builder.getContext());
6739 std::string name =
6740 converter.getRecordTypeFieldName(getLastSym(*x));
6741 if (auto recTy = mlir::dyn_cast<fir::RecordType>(ty)) {
6742 ty = recTy.getType(name);
6743 auto fld = builder.create<fir::FieldIndexOp>(
6744 loc, fieldTy, name, recTy, fir::getTypeParams(arrayExv));
6745 addComponentList(ty, {fld});
6746 if (index != revPath.size() - 1 || !isPointerAssignment()) {
6747 // Need an intermediate dereference if the boxed value
6748 // appears in the middle of the component path or if it is
6749 // on the right and this is not a pointer assignment.
6750 if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(ty)) {
6751 auto currentFunc = components.getExtendCoorRef();
6752 auto loc = getLoc();
6753 auto *bldr = &converter.getFirOpBuilder();
6754 auto newCoorRef = [=](mlir::Value val) -> mlir::Value {
6755 return bldr->create<fir::LoadOp>(loc, currentFunc(val));
6757 components.extendCoorRef = newCoorRef;
6758 deref = true;
6761 } else if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(ty)) {
6762 ty = fir::unwrapRefType(boxTy.getEleTy());
6763 auto recTy = mlir::cast<fir::RecordType>(ty);
6764 ty = recTy.getType(name);
6765 auto fld = builder.create<fir::FieldIndexOp>(
6766 loc, fieldTy, name, recTy, fir::getTypeParams(arrayExv));
6767 extendComponent(components, ty, {fld});
6768 } else {
6769 TODO(loc, "other component type");
6773 atBase = false;
6774 ++index;
6776 ty = fir::unwrapSequenceType(ty);
6777 components.applied = true;
6778 return ty;
6781 llvm::SmallVector<mlir::Value> genSubstringBounds(ComponentPath &components) {
6782 llvm::SmallVector<mlir::Value> result;
6783 if (components.substring)
6784 populateBounds(result, components.substring);
6785 return result;
6788 CC applyPathToArrayLoad(fir::ArrayLoadOp load, ComponentPath &components) {
6789 mlir::Location loc = getLoc();
6790 auto revPath = components.reversePath;
6791 fir::ExtendedValue arrayExv =
6792 arrayLoadExtValue(builder, loc, load, {}, load);
6793 mlir::Type eleTy = lowerPath(arrayExv, components);
6794 auto currentPC = components.pc;
6795 auto pc = [=, prefix = components.prefixComponents,
6796 suffix = components.suffixComponents](IterSpace iters) {
6797 // Add path prefix and suffix.
6798 return IterationSpace(currentPC(iters), prefix, suffix);
6800 components.resetPC();
6801 llvm::SmallVector<mlir::Value> substringBounds =
6802 genSubstringBounds(components);
6803 if (isProjectedCopyInCopyOut()) {
6804 destination = load;
6805 auto lambda = [=, esp = this->explicitSpace](IterSpace iters) mutable {
6806 mlir::Value innerArg = esp->findArgumentOfLoad(load);
6807 if (isAdjustedArrayElementType(eleTy)) {
6808 mlir::Type eleRefTy = builder.getRefType(eleTy);
6809 auto arrayOp = builder.create<fir::ArrayAccessOp>(
6810 loc, eleRefTy, innerArg, iters.iterVec(),
6811 fir::factory::getTypeParams(loc, builder, load));
6812 if (auto charTy = mlir::dyn_cast<fir::CharacterType>(eleTy)) {
6813 mlir::Value dstLen = fir::factory::genLenOfCharacter(
6814 builder, loc, load, iters.iterVec(), substringBounds);
6815 fir::ArrayAmendOp amend = createCharArrayAmend(
6816 loc, builder, arrayOp, dstLen, iters.elementExv(), innerArg,
6817 substringBounds);
6818 return arrayLoadExtValue(builder, loc, load, iters.iterVec(), amend,
6819 dstLen);
6821 if (fir::isa_derived(eleTy)) {
6822 fir::ArrayAmendOp amend =
6823 createDerivedArrayAmend(loc, load, builder, arrayOp,
6824 iters.elementExv(), eleTy, innerArg);
6825 return arrayLoadExtValue(builder, loc, load, iters.iterVec(),
6826 amend);
6828 assert(mlir::isa<fir::SequenceType>(eleTy));
6829 TODO(loc, "array (as element) assignment");
6831 if (components.hasExtendCoorRef()) {
6832 auto eleBoxTy =
6833 fir::applyPathToType(innerArg.getType(), iters.iterVec());
6834 if (!eleBoxTy || !mlir::isa<fir::BoxType>(eleBoxTy))
6835 TODO(loc, "assignment in a FORALL involving a designator with a "
6836 "POINTER or ALLOCATABLE component part-ref");
6837 auto arrayOp = builder.create<fir::ArrayAccessOp>(
6838 loc, builder.getRefType(eleBoxTy), innerArg, iters.iterVec(),
6839 fir::factory::getTypeParams(loc, builder, load));
6840 mlir::Value addr = components.getExtendCoorRef()(arrayOp);
6841 components.resetExtendCoorRef();
6842 // When the lhs is a boxed value and the context is not a pointer
6843 // assignment, then insert the dereference of the box before any
6844 // conversion and store.
6845 if (!isPointerAssignment()) {
6846 if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(eleTy)) {
6847 eleTy = fir::boxMemRefType(boxTy);
6848 addr = builder.create<fir::BoxAddrOp>(loc, eleTy, addr);
6849 eleTy = fir::unwrapRefType(eleTy);
6852 auto ele = convertElementForUpdate(loc, eleTy, iters.getElement());
6853 builder.create<fir::StoreOp>(loc, ele, addr);
6854 auto amend = builder.create<fir::ArrayAmendOp>(
6855 loc, innerArg.getType(), innerArg, arrayOp);
6856 return arrayLoadExtValue(builder, loc, load, iters.iterVec(), amend);
6858 auto ele = convertElementForUpdate(loc, eleTy, iters.getElement());
6859 auto update = builder.create<fir::ArrayUpdateOp>(
6860 loc, innerArg.getType(), innerArg, ele, iters.iterVec(),
6861 fir::factory::getTypeParams(loc, builder, load));
6862 return arrayLoadExtValue(builder, loc, load, iters.iterVec(), update);
6864 return [=](IterSpace iters) mutable { return lambda(pc(iters)); };
6866 if (isCustomCopyInCopyOut()) {
6867 // Create an array_modify to get the LHS element address and indicate
6868 // the assignment, and create the call to the user defined assignment.
6869 destination = load;
6870 auto lambda = [=](IterSpace iters) mutable {
6871 mlir::Value innerArg = explicitSpace->findArgumentOfLoad(load);
6872 mlir::Type refEleTy =
6873 fir::isa_ref_type(eleTy) ? eleTy : builder.getRefType(eleTy);
6874 auto arrModify = builder.create<fir::ArrayModifyOp>(
6875 loc, mlir::TypeRange{refEleTy, innerArg.getType()}, innerArg,
6876 iters.iterVec(), load.getTypeparams());
6877 return arrayLoadExtValue(builder, loc, load, iters.iterVec(),
6878 arrModify.getResult(1));
6880 return [=](IterSpace iters) mutable { return lambda(pc(iters)); };
6882 auto lambda = [=, semant = this->semant](IterSpace iters) mutable {
6883 if (semant == ConstituentSemantics::RefOpaque ||
6884 isAdjustedArrayElementType(eleTy)) {
6885 mlir::Type resTy = builder.getRefType(eleTy);
6886 // Use array element reference semantics.
6887 auto access = builder.create<fir::ArrayAccessOp>(
6888 loc, resTy, load, iters.iterVec(),
6889 fir::factory::getTypeParams(loc, builder, load));
6890 mlir::Value newBase = access;
6891 if (fir::isa_char(eleTy)) {
6892 mlir::Value dstLen = fir::factory::genLenOfCharacter(
6893 builder, loc, load, iters.iterVec(), substringBounds);
6894 if (!substringBounds.empty()) {
6895 fir::CharBoxValue charDst{access, dstLen};
6896 fir::factory::CharacterExprHelper helper{builder, loc};
6897 charDst = helper.createSubstring(charDst, substringBounds);
6898 newBase = charDst.getAddr();
6900 return arrayLoadExtValue(builder, loc, load, iters.iterVec(), newBase,
6901 dstLen);
6903 return arrayLoadExtValue(builder, loc, load, iters.iterVec(), newBase);
6905 if (components.hasExtendCoorRef()) {
6906 auto eleBoxTy = fir::applyPathToType(load.getType(), iters.iterVec());
6907 if (!eleBoxTy || !mlir::isa<fir::BoxType>(eleBoxTy))
6908 TODO(loc, "assignment in a FORALL involving a designator with a "
6909 "POINTER or ALLOCATABLE component part-ref");
6910 auto access = builder.create<fir::ArrayAccessOp>(
6911 loc, builder.getRefType(eleBoxTy), load, iters.iterVec(),
6912 fir::factory::getTypeParams(loc, builder, load));
6913 mlir::Value addr = components.getExtendCoorRef()(access);
6914 components.resetExtendCoorRef();
6915 return arrayLoadExtValue(builder, loc, load, iters.iterVec(), addr);
6917 if (isPointerAssignment()) {
6918 auto eleTy = fir::applyPathToType(load.getType(), iters.iterVec());
6919 if (!mlir::isa<fir::BoxType>(eleTy)) {
6920 // Rhs is a regular expression that will need to be boxed before
6921 // assigning to the boxed variable.
6922 auto typeParams = fir::factory::getTypeParams(loc, builder, load);
6923 auto access = builder.create<fir::ArrayAccessOp>(
6924 loc, builder.getRefType(eleTy), load, iters.iterVec(),
6925 typeParams);
6926 auto addr = components.getExtendCoorRef()(access);
6927 components.resetExtendCoorRef();
6928 auto ptrEleTy = fir::PointerType::get(eleTy);
6929 auto ptrAddr = builder.createConvert(loc, ptrEleTy, addr);
6930 auto boxTy = fir::BoxType::get(ptrEleTy);
6931 // FIXME: The typeparams to the load may be different than those of
6932 // the subobject.
6933 if (components.hasExtendCoorRef())
6934 TODO(loc, "need to adjust typeparameter(s) to reflect the final "
6935 "component");
6936 mlir::Value embox =
6937 builder.create<fir::EmboxOp>(loc, boxTy, ptrAddr,
6938 /*shape=*/mlir::Value{},
6939 /*slice=*/mlir::Value{}, typeParams);
6940 return arrayLoadExtValue(builder, loc, load, iters.iterVec(), embox);
6943 auto fetch = builder.create<fir::ArrayFetchOp>(
6944 loc, eleTy, load, iters.iterVec(), load.getTypeparams());
6945 return arrayLoadExtValue(builder, loc, load, iters.iterVec(), fetch);
6947 return [=](IterSpace iters) mutable { return lambda(pc(iters)); };
6950 template <typename A>
6951 CC genImplicitArrayAccess(const A &x, ComponentPath &components) {
6952 components.reversePath.push_back(ImplicitSubscripts{});
6953 ExtValue exv = asScalarRef(x);
6954 lowerPath(exv, components);
6955 auto lambda = genarr(exv, components);
6956 return [=](IterSpace iters) { return lambda(components.pc(iters)); };
6958 CC genImplicitArrayAccess(const Fortran::evaluate::NamedEntity &x,
6959 ComponentPath &components) {
6960 if (x.IsSymbol())
6961 return genImplicitArrayAccess(getFirstSym(x), components);
6962 return genImplicitArrayAccess(x.GetComponent(), components);
6965 CC genImplicitArrayAccess(const Fortran::semantics::Symbol &x,
6966 ComponentPath &components) {
6967 mlir::Value ptrVal = nullptr;
6968 if (x.test(Fortran::semantics::Symbol::Flag::CrayPointee)) {
6969 Fortran::semantics::SymbolRef ptrSym{
6970 Fortran::semantics::GetCrayPointer(x)};
6971 ExtValue ptr = converter.getSymbolExtendedValue(ptrSym);
6972 ptrVal = fir::getBase(ptr);
6974 components.reversePath.push_back(ImplicitSubscripts{});
6975 ExtValue exv = asScalarRef(x);
6976 lowerPath(exv, components);
6977 auto lambda = genarr(exv, components, ptrVal);
6978 return [=](IterSpace iters) { return lambda(components.pc(iters)); };
6981 template <typename A>
6982 CC genAsScalar(const A &x) {
6983 mlir::Location loc = getLoc();
6984 if (isProjectedCopyInCopyOut()) {
6985 return [=, &x, builder = &converter.getFirOpBuilder()](
6986 IterSpace iters) -> ExtValue {
6987 ExtValue exv = asScalarRef(x);
6988 mlir::Value addr = fir::getBase(exv);
6989 mlir::Type eleTy = fir::unwrapRefType(addr.getType());
6990 if (isAdjustedArrayElementType(eleTy)) {
6991 if (fir::isa_char(eleTy)) {
6992 fir::factory::CharacterExprHelper{*builder, loc}.createAssign(
6993 exv, iters.elementExv());
6994 } else if (fir::isa_derived(eleTy)) {
6995 TODO(loc, "assignment of derived type");
6996 } else {
6997 fir::emitFatalError(loc, "array type not expected in scalar");
6999 } else {
7000 auto eleVal = convertElementForUpdate(loc, eleTy, iters.getElement());
7001 builder->create<fir::StoreOp>(loc, eleVal, addr);
7003 return exv;
7006 return [=, &x](IterSpace) { return asScalar(x); };
7009 bool tailIsPointerInPointerAssignment(const Fortran::semantics::Symbol &x,
7010 ComponentPath &components) {
7011 return isPointerAssignment() && Fortran::semantics::IsPointer(x) &&
7012 !components.hasComponents();
7014 bool tailIsPointerInPointerAssignment(const Fortran::evaluate::Component &x,
7015 ComponentPath &components) {
7016 return tailIsPointerInPointerAssignment(getLastSym(x), components);
7019 CC genarr(const Fortran::semantics::Symbol &x, ComponentPath &components) {
7020 if (explicitSpaceIsActive()) {
7021 if (x.Rank() > 0 && !tailIsPointerInPointerAssignment(x, components))
7022 components.reversePath.push_back(ImplicitSubscripts{});
7023 if (fir::ArrayLoadOp load = explicitSpace->findBinding(&x))
7024 return applyPathToArrayLoad(load, components);
7025 } else {
7026 return genImplicitArrayAccess(x, components);
7028 if (pathIsEmpty(components))
7029 return components.substring ? genAsScalar(*components.substring)
7030 : genAsScalar(x);
7031 mlir::Location loc = getLoc();
7032 return [=](IterSpace) -> ExtValue {
7033 fir::emitFatalError(loc, "reached symbol with path");
7037 /// Lower a component path with or without rank.
7038 /// Example: <code>array%baz%qux%waldo</code>
7039 CC genarr(const Fortran::evaluate::Component &x, ComponentPath &components) {
7040 if (explicitSpaceIsActive()) {
7041 if (x.base().Rank() == 0 && x.Rank() > 0 &&
7042 !tailIsPointerInPointerAssignment(x, components))
7043 components.reversePath.push_back(ImplicitSubscripts{});
7044 if (fir::ArrayLoadOp load = explicitSpace->findBinding(&x))
7045 return applyPathToArrayLoad(load, components);
7046 } else {
7047 if (x.base().Rank() == 0)
7048 return genImplicitArrayAccess(x, components);
7050 bool atEnd = pathIsEmpty(components);
7051 if (!getLastSym(x).test(Fortran::semantics::Symbol::Flag::ParentComp))
7052 // Skip parent components; their components are placed directly in the
7053 // object.
7054 components.reversePath.push_back(&x);
7055 auto result = genarr(x.base(), components);
7056 if (components.applied)
7057 return result;
7058 if (atEnd)
7059 return genAsScalar(x);
7060 mlir::Location loc = getLoc();
7061 return [=](IterSpace) -> ExtValue {
7062 fir::emitFatalError(loc, "reached component with path");
7066 /// Array reference with subscripts. If this has rank > 0, this is a form
7067 /// of an array section (slice).
7069 /// There are two "slicing" primitives that may be applied on a dimension by
7070 /// dimension basis: (1) triple notation and (2) vector addressing. Since
7071 /// dimensions can be selectively sliced, some dimensions may contain
7072 /// regular scalar expressions and those dimensions do not participate in
7073 /// the array expression evaluation.
7074 CC genarr(const Fortran::evaluate::ArrayRef &x, ComponentPath &components) {
7075 if (explicitSpaceIsActive()) {
7076 if (Fortran::lower::isRankedArrayAccess(x))
7077 components.reversePath.push_back(ImplicitSubscripts{});
7078 if (fir::ArrayLoadOp load = explicitSpace->findBinding(&x)) {
7079 components.reversePath.push_back(&x);
7080 return applyPathToArrayLoad(load, components);
7082 } else {
7083 if (Fortran::lower::isRankedArrayAccess(x)) {
7084 components.reversePath.push_back(&x);
7085 return genImplicitArrayAccess(x.base(), components);
7088 bool atEnd = pathIsEmpty(components);
7089 components.reversePath.push_back(&x);
7090 auto result = genarr(x.base(), components);
7091 if (components.applied)
7092 return result;
7093 mlir::Location loc = getLoc();
7094 if (atEnd) {
7095 if (x.Rank() == 0)
7096 return genAsScalar(x);
7097 fir::emitFatalError(loc, "expected scalar");
7099 return [=](IterSpace) -> ExtValue {
7100 fir::emitFatalError(loc, "reached arrayref with path");
7104 CC genarr(const Fortran::evaluate::CoarrayRef &x, ComponentPath &components) {
7105 TODO(getLoc(), "coarray: reference to a coarray in an expression");
7108 CC genarr(const Fortran::evaluate::NamedEntity &x,
7109 ComponentPath &components) {
7110 return x.IsSymbol() ? genarr(getFirstSym(x), components)
7111 : genarr(x.GetComponent(), components);
7114 CC genarr(const Fortran::evaluate::DataRef &x, ComponentPath &components) {
7115 return Fortran::common::visit(
7116 [&](const auto &v) { return genarr(v, components); }, x.u);
7119 bool pathIsEmpty(const ComponentPath &components) {
7120 return components.reversePath.empty();
7123 explicit ArrayExprLowering(Fortran::lower::AbstractConverter &converter,
7124 Fortran::lower::StatementContext &stmtCtx,
7125 Fortran::lower::SymMap &symMap)
7126 : converter{converter}, builder{converter.getFirOpBuilder()},
7127 stmtCtx{stmtCtx}, symMap{symMap} {}
7129 explicit ArrayExprLowering(Fortran::lower::AbstractConverter &converter,
7130 Fortran::lower::StatementContext &stmtCtx,
7131 Fortran::lower::SymMap &symMap,
7132 ConstituentSemantics sem)
7133 : converter{converter}, builder{converter.getFirOpBuilder()},
7134 stmtCtx{stmtCtx}, symMap{symMap}, semant{sem} {}
7136 explicit ArrayExprLowering(Fortran::lower::AbstractConverter &converter,
7137 Fortran::lower::StatementContext &stmtCtx,
7138 Fortran::lower::SymMap &symMap,
7139 ConstituentSemantics sem,
7140 Fortran::lower::ExplicitIterSpace *expSpace,
7141 Fortran::lower::ImplicitIterSpace *impSpace)
7142 : converter{converter}, builder{converter.getFirOpBuilder()},
7143 stmtCtx{stmtCtx}, symMap{symMap},
7144 explicitSpace((expSpace && expSpace->isActive()) ? expSpace : nullptr),
7145 implicitSpace((impSpace && !impSpace->empty()) ? impSpace : nullptr),
7146 semant{sem} {
7147 // Generate any mask expressions, as necessary. This is the compute step
7148 // that creates the effective masks. See 10.2.3.2 in particular.
7149 genMasks();
7152 mlir::Location getLoc() { return converter.getCurrentLocation(); }
7154 /// Array appears in a lhs context such that it is assigned after the rhs is
7155 /// fully evaluated.
7156 inline bool isCopyInCopyOut() {
7157 return semant == ConstituentSemantics::CopyInCopyOut;
7160 /// Array appears in a lhs (or temp) context such that a projected,
7161 /// discontiguous subspace of the array is assigned after the rhs is fully
7162 /// evaluated. That is, the rhs array value is merged into a section of the
7163 /// lhs array.
7164 inline bool isProjectedCopyInCopyOut() {
7165 return semant == ConstituentSemantics::ProjectedCopyInCopyOut;
7168 // ???: Do we still need this?
7169 inline bool isCustomCopyInCopyOut() {
7170 return semant == ConstituentSemantics::CustomCopyInCopyOut;
7173 /// Are we lowering in a left-hand side context?
7174 inline bool isLeftHandSide() {
7175 return isCopyInCopyOut() || isProjectedCopyInCopyOut() ||
7176 isCustomCopyInCopyOut();
7179 /// Array appears in a context where it must be boxed.
7180 inline bool isBoxValue() { return semant == ConstituentSemantics::BoxValue; }
7182 /// Array appears in a context where differences in the memory reference can
7183 /// be observable in the computational results. For example, an array
7184 /// element is passed to an impure procedure.
7185 inline bool isReferentiallyOpaque() {
7186 return semant == ConstituentSemantics::RefOpaque;
7189 /// Array appears in a context where it is passed as a VALUE argument.
7190 inline bool isValueAttribute() {
7191 return semant == ConstituentSemantics::ByValueArg;
7194 /// Semantics to use when lowering the next array path.
7195 /// If no value was set, the path uses the same semantics as the array.
7196 inline ConstituentSemantics nextPathSemantics() {
7197 if (nextPathSemant) {
7198 ConstituentSemantics sema = nextPathSemant.value();
7199 nextPathSemant.reset();
7200 return sema;
7203 return semant;
7206 /// Can the loops over the expression be unordered?
7207 inline bool isUnordered() const { return unordered; }
7209 void setUnordered(bool b) { unordered = b; }
7211 inline bool isPointerAssignment() const { return lbounds.has_value(); }
7213 inline bool isBoundsSpec() const {
7214 return isPointerAssignment() && !ubounds.has_value();
7217 inline bool isBoundsRemap() const {
7218 return isPointerAssignment() && ubounds.has_value();
7221 void setPointerAssignmentBounds(
7222 const llvm::SmallVector<mlir::Value> &lbs,
7223 std::optional<llvm::SmallVector<mlir::Value>> ubs) {
7224 lbounds = lbs;
7225 ubounds = ubs;
7228 void setLoweredProcRef(const Fortran::evaluate::ProcedureRef *procRef) {
7229 loweredProcRef = procRef;
7232 Fortran::lower::AbstractConverter &converter;
7233 fir::FirOpBuilder &builder;
7234 Fortran::lower::StatementContext &stmtCtx;
7235 bool elementCtx = false;
7236 Fortran::lower::SymMap &symMap;
7237 /// The continuation to generate code to update the destination.
7238 std::optional<CC> ccStoreToDest;
7239 std::optional<std::function<void(llvm::ArrayRef<mlir::Value>)>> ccPrelude;
7240 std::optional<std::function<fir::ArrayLoadOp(llvm::ArrayRef<mlir::Value>)>>
7241 ccLoadDest;
7242 /// The destination is the loaded array into which the results will be
7243 /// merged.
7244 fir::ArrayLoadOp destination;
7245 /// The shape of the destination.
7246 llvm::SmallVector<mlir::Value> destShape;
7247 /// List of arrays in the expression that have been loaded.
7248 llvm::SmallVector<ArrayOperand> arrayOperands;
7249 /// If there is a user-defined iteration space, explicitShape will hold the
7250 /// information from the front end.
7251 Fortran::lower::ExplicitIterSpace *explicitSpace = nullptr;
7252 Fortran::lower::ImplicitIterSpace *implicitSpace = nullptr;
7253 ConstituentSemantics semant = ConstituentSemantics::RefTransparent;
7254 std::optional<ConstituentSemantics> nextPathSemant;
7255 /// `lbounds`, `ubounds` are used in POINTER value assignments, which may only
7256 /// occur in an explicit iteration space.
7257 std::optional<llvm::SmallVector<mlir::Value>> lbounds;
7258 std::optional<llvm::SmallVector<mlir::Value>> ubounds;
7259 // Can the array expression be evaluated in any order?
7260 // Will be set to false if any of the expression parts prevent this.
7261 bool unordered = true;
7262 // ProcedureRef currently being lowered. Used to retrieve the iteration shape
7263 // in elemental context with passed object.
7264 const Fortran::evaluate::ProcedureRef *loweredProcRef = nullptr;
7266 } // namespace
7268 fir::ExtendedValue Fortran::lower::createSomeExtendedExpression(
7269 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
7270 const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap,
7271 Fortran::lower::StatementContext &stmtCtx) {
7272 LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "expr: ") << '\n');
7273 return ScalarExprLowering{loc, converter, symMap, stmtCtx}.genval(expr);
7276 fir::ExtendedValue Fortran::lower::createSomeInitializerExpression(
7277 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
7278 const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap,
7279 Fortran::lower::StatementContext &stmtCtx) {
7280 LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "expr: ") << '\n');
7281 return ScalarExprLowering{loc, converter, symMap, stmtCtx,
7282 /*inInitializer=*/true}
7283 .genval(expr);
7286 fir::ExtendedValue Fortran::lower::createSomeExtendedAddress(
7287 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
7288 const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap,
7289 Fortran::lower::StatementContext &stmtCtx) {
7290 LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "address: ") << '\n');
7291 return ScalarExprLowering(loc, converter, symMap, stmtCtx).gen(expr);
7294 fir::ExtendedValue Fortran::lower::createInitializerAddress(
7295 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
7296 const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap,
7297 Fortran::lower::StatementContext &stmtCtx) {
7298 LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "address: ") << '\n');
7299 return ScalarExprLowering(loc, converter, symMap, stmtCtx,
7300 /*inInitializer=*/true)
7301 .gen(expr);
7304 void Fortran::lower::createSomeArrayAssignment(
7305 Fortran::lower::AbstractConverter &converter,
7306 const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs,
7307 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) {
7308 LLVM_DEBUG(lhs.AsFortran(llvm::dbgs() << "onto array: ") << '\n';
7309 rhs.AsFortran(llvm::dbgs() << "assign expression: ") << '\n';);
7310 ArrayExprLowering::lowerArrayAssignment(converter, symMap, stmtCtx, lhs, rhs);
7313 void Fortran::lower::createSomeArrayAssignment(
7314 Fortran::lower::AbstractConverter &converter, const fir::ExtendedValue &lhs,
7315 const Fortran::lower::SomeExpr &rhs, Fortran::lower::SymMap &symMap,
7316 Fortran::lower::StatementContext &stmtCtx) {
7317 LLVM_DEBUG(llvm::dbgs() << "onto array: " << lhs << '\n';
7318 rhs.AsFortran(llvm::dbgs() << "assign expression: ") << '\n';);
7319 ArrayExprLowering::lowerArrayAssignment(converter, symMap, stmtCtx, lhs, rhs);
7321 void Fortran::lower::createSomeArrayAssignment(
7322 Fortran::lower::AbstractConverter &converter, const fir::ExtendedValue &lhs,
7323 const fir::ExtendedValue &rhs, Fortran::lower::SymMap &symMap,
7324 Fortran::lower::StatementContext &stmtCtx) {
7325 LLVM_DEBUG(llvm::dbgs() << "onto array: " << lhs << '\n';
7326 llvm::dbgs() << "assign expression: " << rhs << '\n';);
7327 ArrayExprLowering::lowerArrayAssignment(converter, symMap, stmtCtx, lhs, rhs);
7330 void Fortran::lower::createAnyMaskedArrayAssignment(
7331 Fortran::lower::AbstractConverter &converter,
7332 const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs,
7333 Fortran::lower::ExplicitIterSpace &explicitSpace,
7334 Fortran::lower::ImplicitIterSpace &implicitSpace,
7335 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) {
7336 LLVM_DEBUG(lhs.AsFortran(llvm::dbgs() << "onto array: ") << '\n';
7337 rhs.AsFortran(llvm::dbgs() << "assign expression: ")
7338 << " given the explicit iteration space:\n"
7339 << explicitSpace << "\n and implied mask conditions:\n"
7340 << implicitSpace << '\n';);
7341 ArrayExprLowering::lowerAnyMaskedArrayAssignment(
7342 converter, symMap, stmtCtx, lhs, rhs, explicitSpace, implicitSpace);
7345 void Fortran::lower::createAllocatableArrayAssignment(
7346 Fortran::lower::AbstractConverter &converter,
7347 const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs,
7348 Fortran::lower::ExplicitIterSpace &explicitSpace,
7349 Fortran::lower::ImplicitIterSpace &implicitSpace,
7350 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) {
7351 LLVM_DEBUG(lhs.AsFortran(llvm::dbgs() << "defining array: ") << '\n';
7352 rhs.AsFortran(llvm::dbgs() << "assign expression: ")
7353 << " given the explicit iteration space:\n"
7354 << explicitSpace << "\n and implied mask conditions:\n"
7355 << implicitSpace << '\n';);
7356 ArrayExprLowering::lowerAllocatableArrayAssignment(
7357 converter, symMap, stmtCtx, lhs, rhs, explicitSpace, implicitSpace);
7360 void Fortran::lower::createArrayOfPointerAssignment(
7361 Fortran::lower::AbstractConverter &converter,
7362 const Fortran::lower::SomeExpr &lhs, const Fortran::lower::SomeExpr &rhs,
7363 Fortran::lower::ExplicitIterSpace &explicitSpace,
7364 Fortran::lower::ImplicitIterSpace &implicitSpace,
7365 const llvm::SmallVector<mlir::Value> &lbounds,
7366 std::optional<llvm::SmallVector<mlir::Value>> ubounds,
7367 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) {
7368 LLVM_DEBUG(lhs.AsFortran(llvm::dbgs() << "defining pointer: ") << '\n';
7369 rhs.AsFortran(llvm::dbgs() << "assign expression: ")
7370 << " given the explicit iteration space:\n"
7371 << explicitSpace << "\n and implied mask conditions:\n"
7372 << implicitSpace << '\n';);
7373 assert(explicitSpace.isActive() && "must be in FORALL construct");
7374 ArrayExprLowering::lowerArrayOfPointerAssignment(
7375 converter, symMap, stmtCtx, lhs, rhs, explicitSpace, implicitSpace,
7376 lbounds, ubounds);
7379 fir::ExtendedValue Fortran::lower::createSomeArrayTempValue(
7380 Fortran::lower::AbstractConverter &converter,
7381 const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap,
7382 Fortran::lower::StatementContext &stmtCtx) {
7383 LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "array value: ") << '\n');
7384 return ArrayExprLowering::lowerNewArrayExpression(converter, symMap, stmtCtx,
7385 expr);
7388 void Fortran::lower::createLazyArrayTempValue(
7389 Fortran::lower::AbstractConverter &converter,
7390 const Fortran::lower::SomeExpr &expr, mlir::Value raggedHeader,
7391 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx) {
7392 LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "array value: ") << '\n');
7393 ArrayExprLowering::lowerLazyArrayExpression(converter, symMap, stmtCtx, expr,
7394 raggedHeader);
7397 fir::ExtendedValue
7398 Fortran::lower::createSomeArrayBox(Fortran::lower::AbstractConverter &converter,
7399 const Fortran::lower::SomeExpr &expr,
7400 Fortran::lower::SymMap &symMap,
7401 Fortran::lower::StatementContext &stmtCtx) {
7402 LLVM_DEBUG(expr.AsFortran(llvm::dbgs() << "box designator: ") << '\n');
7403 return ArrayExprLowering::lowerBoxedArrayExpression(converter, symMap,
7404 stmtCtx, expr);
7407 fir::MutableBoxValue Fortran::lower::createMutableBox(
7408 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
7409 const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap) {
7410 // MutableBox lowering StatementContext does not need to be propagated
7411 // to the caller because the result value is a variable, not a temporary
7412 // expression. The StatementContext clean-up can occur before using the
7413 // resulting MutableBoxValue. Variables of all other types are handled in the
7414 // bridge.
7415 Fortran::lower::StatementContext dummyStmtCtx;
7416 return ScalarExprLowering{loc, converter, symMap, dummyStmtCtx}
7417 .genMutableBoxValue(expr);
7420 bool Fortran::lower::isParentComponent(const Fortran::lower::SomeExpr &expr) {
7421 if (const Fortran::semantics::Symbol * symbol{GetLastSymbol(expr)}) {
7422 if (symbol->test(Fortran::semantics::Symbol::Flag::ParentComp))
7423 return true;
7425 return false;
7428 // Handling special case where the last component is referring to the
7429 // parent component.
7431 // TYPE t
7432 // integer :: a
7433 // END TYPE
7434 // TYPE, EXTENDS(t) :: t2
7435 // integer :: b
7436 // END TYPE
7437 // TYPE(t2) :: y(2)
7438 // TYPE(t2) :: a
7439 // y(:)%t ! just need to update the box with a slice pointing to the first
7440 // ! component of `t`.
7441 // a%t ! simple conversion to TYPE(t).
7442 fir::ExtendedValue Fortran::lower::updateBoxForParentComponent(
7443 Fortran::lower::AbstractConverter &converter, fir::ExtendedValue box,
7444 const Fortran::lower::SomeExpr &expr) {
7445 mlir::Location loc = converter.getCurrentLocation();
7446 auto &builder = converter.getFirOpBuilder();
7447 mlir::Value boxBase = fir::getBase(box);
7448 mlir::Operation *op = boxBase.getDefiningOp();
7449 mlir::Type actualTy = converter.genType(expr);
7451 if (op) {
7452 if (auto embox = mlir::dyn_cast<fir::EmboxOp>(op)) {
7453 auto newBox = builder.create<fir::EmboxOp>(
7454 loc, fir::BoxType::get(actualTy), embox.getMemref(), embox.getShape(),
7455 embox.getSlice(), embox.getTypeparams());
7456 return fir::substBase(box, newBox);
7458 if (auto rebox = mlir::dyn_cast<fir::ReboxOp>(op)) {
7459 auto newBox = builder.create<fir::ReboxOp>(
7460 loc, fir::BoxType::get(actualTy), rebox.getBox(), rebox.getShape(),
7461 rebox.getSlice());
7462 return fir::substBase(box, newBox);
7466 mlir::Value empty;
7467 mlir::ValueRange emptyRange;
7468 return builder.create<fir::ReboxOp>(loc, fir::BoxType::get(actualTy), boxBase,
7469 /*shape=*/empty,
7470 /*slice=*/empty);
7473 fir::ExtendedValue Fortran::lower::createBoxValue(
7474 mlir::Location loc, Fortran::lower::AbstractConverter &converter,
7475 const Fortran::lower::SomeExpr &expr, Fortran::lower::SymMap &symMap,
7476 Fortran::lower::StatementContext &stmtCtx) {
7477 if (expr.Rank() > 0 && Fortran::evaluate::IsVariable(expr) &&
7478 !Fortran::evaluate::HasVectorSubscript(expr)) {
7479 fir::ExtendedValue result =
7480 Fortran::lower::createSomeArrayBox(converter, expr, symMap, stmtCtx);
7481 if (isParentComponent(expr))
7482 result = updateBoxForParentComponent(converter, result, expr);
7483 return result;
7485 fir::ExtendedValue addr = Fortran::lower::createSomeExtendedAddress(
7486 loc, converter, expr, symMap, stmtCtx);
7487 fir::ExtendedValue result = fir::BoxValue(
7488 converter.getFirOpBuilder().createBox(loc, addr, addr.isPolymorphic()));
7489 if (isParentComponent(expr))
7490 result = updateBoxForParentComponent(converter, result, expr);
7491 return result;
7494 mlir::Value Fortran::lower::createSubroutineCall(
7495 AbstractConverter &converter, const evaluate::ProcedureRef &call,
7496 ExplicitIterSpace &explicitIterSpace, ImplicitIterSpace &implicitIterSpace,
7497 SymMap &symMap, StatementContext &stmtCtx, bool isUserDefAssignment) {
7498 mlir::Location loc = converter.getCurrentLocation();
7500 if (isUserDefAssignment) {
7501 assert(call.arguments().size() == 2);
7502 const auto *lhs = call.arguments()[0].value().UnwrapExpr();
7503 const auto *rhs = call.arguments()[1].value().UnwrapExpr();
7504 assert(lhs && rhs &&
7505 "user defined assignment arguments must be expressions");
7506 if (call.IsElemental() && lhs->Rank() > 0) {
7507 // Elemental user defined assignment has special requirements to deal with
7508 // LHS/RHS overlaps. See 10.2.1.5 p2.
7509 ArrayExprLowering::lowerElementalUserAssignment(
7510 converter, symMap, stmtCtx, explicitIterSpace, implicitIterSpace,
7511 call);
7512 } else if (explicitIterSpace.isActive() && lhs->Rank() == 0) {
7513 // Scalar defined assignment (elemental or not) in a FORALL context.
7514 mlir::func::FuncOp func =
7515 Fortran::lower::CallerInterface(call, converter).getFuncOp();
7516 ArrayExprLowering::lowerScalarUserAssignment(
7517 converter, symMap, stmtCtx, explicitIterSpace, func, *lhs, *rhs);
7518 } else if (explicitIterSpace.isActive()) {
7519 // TODO: need to array fetch/modify sub-arrays?
7520 TODO(loc, "non elemental user defined array assignment inside FORALL");
7521 } else {
7522 if (!implicitIterSpace.empty())
7523 fir::emitFatalError(
7524 loc,
7525 "C1032: user defined assignment inside WHERE must be elemental");
7526 // Non elemental user defined assignment outside of FORALL and WHERE.
7527 // FIXME: The non elemental user defined assignment case with array
7528 // arguments must be take into account potential overlap. So far the front
7529 // end does not add parentheses around the RHS argument in the call as it
7530 // should according to 15.4.3.4.3 p2.
7531 Fortran::lower::createSomeExtendedExpression(
7532 loc, converter, toEvExpr(call), symMap, stmtCtx);
7534 return {};
7537 assert(implicitIterSpace.empty() && !explicitIterSpace.isActive() &&
7538 "subroutine calls are not allowed inside WHERE and FORALL");
7540 if (isElementalProcWithArrayArgs(call)) {
7541 ArrayExprLowering::lowerElementalSubroutine(converter, symMap, stmtCtx,
7542 toEvExpr(call));
7543 return {};
7545 // Simple subroutine call, with potential alternate return.
7546 auto res = Fortran::lower::createSomeExtendedExpression(
7547 loc, converter, toEvExpr(call), symMap, stmtCtx);
7548 return fir::getBase(res);
7551 template <typename A>
7552 fir::ArrayLoadOp genArrayLoad(mlir::Location loc,
7553 Fortran::lower::AbstractConverter &converter,
7554 fir::FirOpBuilder &builder, const A *x,
7555 Fortran::lower::SymMap &symMap,
7556 Fortran::lower::StatementContext &stmtCtx) {
7557 auto exv = ScalarExprLowering{loc, converter, symMap, stmtCtx}.gen(*x);
7558 mlir::Value addr = fir::getBase(exv);
7559 mlir::Value shapeOp = builder.createShape(loc, exv);
7560 mlir::Type arrTy = fir::dyn_cast_ptrOrBoxEleTy(addr.getType());
7561 return builder.create<fir::ArrayLoadOp>(loc, arrTy, addr, shapeOp,
7562 /*slice=*/mlir::Value{},
7563 fir::getTypeParams(exv));
7565 template <>
7566 fir::ArrayLoadOp
7567 genArrayLoad(mlir::Location loc, Fortran::lower::AbstractConverter &converter,
7568 fir::FirOpBuilder &builder, const Fortran::evaluate::ArrayRef *x,
7569 Fortran::lower::SymMap &symMap,
7570 Fortran::lower::StatementContext &stmtCtx) {
7571 if (x->base().IsSymbol())
7572 return genArrayLoad(loc, converter, builder, &getLastSym(x->base()), symMap,
7573 stmtCtx);
7574 return genArrayLoad(loc, converter, builder, &x->base().GetComponent(),
7575 symMap, stmtCtx);
7578 void Fortran::lower::createArrayLoads(
7579 Fortran::lower::AbstractConverter &converter,
7580 Fortran::lower::ExplicitIterSpace &esp, Fortran::lower::SymMap &symMap) {
7581 std::size_t counter = esp.getCounter();
7582 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
7583 mlir::Location loc = converter.getCurrentLocation();
7584 Fortran::lower::StatementContext &stmtCtx = esp.stmtContext();
7585 // Gen the fir.array_load ops.
7586 auto genLoad = [&](const auto *x) -> fir::ArrayLoadOp {
7587 return genArrayLoad(loc, converter, builder, x, symMap, stmtCtx);
7589 if (esp.lhsBases[counter]) {
7590 auto &base = *esp.lhsBases[counter];
7591 auto load = Fortran::common::visit(genLoad, base);
7592 esp.initialArgs.push_back(load);
7593 esp.resetInnerArgs();
7594 esp.bindLoad(base, load);
7596 for (const auto &base : esp.rhsBases[counter])
7597 esp.bindLoad(base, Fortran::common::visit(genLoad, base));
7600 void Fortran::lower::createArrayMergeStores(
7601 Fortran::lower::AbstractConverter &converter,
7602 Fortran::lower::ExplicitIterSpace &esp) {
7603 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
7604 mlir::Location loc = converter.getCurrentLocation();
7605 builder.setInsertionPointAfter(esp.getOuterLoop());
7606 // Gen the fir.array_merge_store ops for all LHS arrays.
7607 for (auto i : llvm::enumerate(esp.getOuterLoop().getResults()))
7608 if (std::optional<fir::ArrayLoadOp> ldOpt = esp.getLhsLoad(i.index())) {
7609 fir::ArrayLoadOp load = *ldOpt;
7610 builder.create<fir::ArrayMergeStoreOp>(loc, load, i.value(),
7611 load.getMemref(), load.getSlice(),
7612 load.getTypeparams());
7614 if (esp.loopCleanup) {
7615 (*esp.loopCleanup)(builder);
7616 esp.loopCleanup = std::nullopt;
7618 esp.initialArgs.clear();
7619 esp.innerArgs.clear();
7620 esp.outerLoop = std::nullopt;
7621 esp.resetBindings();
7622 esp.incrementCounter();
7625 mlir::Value Fortran::lower::addCrayPointerInst(mlir::Location loc,
7626 fir::FirOpBuilder &builder,
7627 mlir::Value ptrVal,
7628 mlir::Type ptrTy,
7629 mlir::Type pteTy) {
7631 mlir::Value empty;
7632 mlir::ValueRange emptyRange;
7633 auto boxTy = fir::BoxType::get(ptrTy);
7634 auto box = builder.create<fir::EmboxOp>(loc, boxTy, ptrVal, empty, empty,
7635 emptyRange);
7636 mlir::Value addrof =
7637 (mlir::isa<fir::ReferenceType>(ptrTy))
7638 ? builder.create<fir::BoxAddrOp>(loc, ptrTy, box)
7639 : builder.create<fir::BoxAddrOp>(loc, builder.getRefType(ptrTy), box);
7641 auto refPtrTy =
7642 builder.getRefType(fir::PointerType::get(fir::dyn_cast_ptrEleTy(pteTy)));
7643 return builder.createConvert(loc, refPtrTy, addrof);