Debian Codegraph @

flang/lib/Lower/DirectivesCommon.h

raw
1 //===-- Lower/DirectivesCommon.h --------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/
10 //
11 //===----------------------------------------------------------------------===//
12 ///
13 /// A location to place directive utilities shared across multiple lowering
14 /// files, e.g. utilities shared in OpenMP and OpenACC. The header file can
15 /// be used for both declarations and templated/inline implementations
16 //===----------------------------------------------------------------------===//
17
18 #ifndef FORTRAN_LOWER_DIRECTIVES_COMMON_H
19 #define FORTRAN_LOWER_DIRECTIVES_COMMON_H
20
21 #include "flang/Common/idioms.h"
22 #include "flang/Evaluate/tools.h"
23 #include "flang/Lower/AbstractConverter.h"
24 #include "flang/Lower/Bridge.h"
25 #include "flang/Lower/ConvertExpr.h"
26 #include "flang/Lower/ConvertVariable.h"
27 #include "flang/Lower/OpenACC.h"
28 #include "flang/Lower/OpenMP.h"
29 #include "flang/Lower/PFTBuilder.h"
30 #include "flang/Lower/StatementContext.h"
31 #include "flang/Lower/Support/Utils.h"
32 #include "flang/Optimizer/Builder/BoxValue.h"
33 #include "flang/Optimizer/Builder/FIRBuilder.h"
34 #include "flang/Optimizer/Builder/HLFIRTools.h"
35 #include "flang/Optimizer/Builder/Todo.h"
36 #include "flang/Optimizer/Dialect/FIRType.h"
37 #include "flang/Optimizer/HLFIR/HLFIROps.h"
38 #include "flang/Parser/parse-tree.h"
39 #include "flang/Semantics/openmp-directive-sets.h"
40 #include "flang/Semantics/tools.h"
41 #include "mlir/Dialect/OpenACC/OpenACC.h"
42 #include "mlir/Dialect/OpenMP/OpenMPDialect.h"
43 #include "mlir/Dialect/SCF/IR/SCF.h"
44 #include "mlir/IR/Value.h"
45 #include "llvm/Frontend/OpenMP/OMPConstants.h"
46 #include <list>
47 #include <type_traits>
48
49 namespace Fortran {
50 namespace lower {
51
52 /// Information gathered to generate bounds operation and data entry/exit
53 /// operations.
54 struct AddrAndBoundsInfo {
55 explicit AddrAndBoundsInfo() {}
56 explicit AddrAndBoundsInfo(mlir::Value addr, mlir::Value rawInput)
57 : addr(addr), rawInput(rawInput) {}
58 explicit AddrAndBoundsInfo(mlir::Value addr, mlir::Value rawInput,
59 mlir::Value isPresent)
60 : addr(addr), rawInput(rawInput), isPresent(isPresent) {}
61 mlir::Value addr = nullptr;
62 mlir::Value rawInput = nullptr;
63 mlir::Value isPresent = nullptr;
64 };
65
66 /// Checks if the assignment statement has a single variable on the RHS.
67 static inline bool checkForSingleVariableOnRHS(
68 const Fortran::parser::AssignmentStmt &assignmentStmt) {
69 const Fortran::parser::Expr &expr{
70 std::get<Fortran::parser::Expr>(assignmentStmt.t)};
71 const Fortran::common::Indirection<Fortran::parser::Designator> *designator =
72 std::get_if<Fortran::common::Indirection<Fortran::parser::Designator>>(
73 &expr.u);
74 return designator != nullptr;
75 }
76
77 /// Checks if the symbol on the LHS of the assignment statement is present in
78 /// the RHS expression.
79 static inline bool
80 checkForSymbolMatch(const Fortran::parser::AssignmentStmt &assignmentStmt) {
81 const auto &var{std::get<Fortran::parser::Variable>(assignmentStmt.t)};
82 const auto &expr{std::get<Fortran::parser::Expr>(assignmentStmt.t)};
83 const auto *e{Fortran::semantics::GetExpr(expr)};
84 const auto *v{Fortran::semantics::GetExpr(var)};
85 auto varSyms{Fortran::evaluate::GetSymbolVector(*v)};
86 const Fortran::semantics::Symbol &varSymbol{*varSyms.front()};
87 for (const Fortran::semantics::Symbol &symbol :
88 Fortran::evaluate::GetSymbolVector(*e))
89 if (varSymbol == symbol)
90 return true;
91 return false;
92 }
93
94 /// Populates \p hint and \p memoryOrder with appropriate clause information
95 /// if present on atomic construct.
96 static inline void genOmpAtomicHintAndMemoryOrderClauses(
97 Fortran::lower::AbstractConverter &converter,
98 const Fortran::parser::OmpAtomicClauseList &clauseList,
99 mlir::IntegerAttr &hint,
100 mlir::omp::ClauseMemoryOrderKindAttr &memoryOrder) {
101 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
102 for (const Fortran::parser::OmpAtomicClause &clause : clauseList.v) {
103 if (const auto *ompClause =
104 std::get_if<Fortran::parser::OmpClause>(&clause.u)) {
105 if (const auto *hintClause =
106 std::get_if<Fortran::parser::OmpClause::Hint>(&ompClause->u)) {
107 const auto *expr = Fortran::semantics::GetExpr(hintClause->v);
108 uint64_t hintExprValue = *Fortran::evaluate::ToInt64(*expr);
109 hint = firOpBuilder.getI64IntegerAttr(hintExprValue);
110 }
111 } else if (const auto *ompMemoryOrderClause =
112 std::get_if<Fortran::parser::OmpMemoryOrderClause>(
113 &clause.u)) {
114 if (std::get_if<Fortran::parser::OmpClause::Acquire>(
115 &ompMemoryOrderClause->v.u)) {
116 memoryOrder = mlir::omp::ClauseMemoryOrderKindAttr::get(
117 firOpBuilder.getContext(),
118 mlir::omp::ClauseMemoryOrderKind::Acquire);
119 } else if (std::get_if<Fortran::parser::OmpClause::Relaxed>(
120 &ompMemoryOrderClause->v.u)) {
121 memoryOrder = mlir::omp::ClauseMemoryOrderKindAttr::get(
122 firOpBuilder.getContext(),
123 mlir::omp::ClauseMemoryOrderKind::Relaxed);
124 } else if (std::get_if<Fortran::parser::OmpClause::SeqCst>(
125 &ompMemoryOrderClause->v.u)) {
126 memoryOrder = mlir::omp::ClauseMemoryOrderKindAttr::get(
127 firOpBuilder.getContext(),
128 mlir::omp::ClauseMemoryOrderKind::Seq_cst);
129 } else if (std::get_if<Fortran::parser::OmpClause::Release>(
130 &ompMemoryOrderClause->v.u)) {
131 memoryOrder = mlir::omp::ClauseMemoryOrderKindAttr::get(
132 firOpBuilder.getContext(),
133 mlir::omp::ClauseMemoryOrderKind::Release);
134 }
135 }
136 }
137 }
138
139 template <typename AtomicListT>
140 static void processOmpAtomicTODO(mlir::Type elementType, mlir::Location loc) {
141 if (!elementType)
142 return;
143 if constexpr (std::is_same<AtomicListT,
144 Fortran::parser::OmpAtomicClauseList>()) {
145 // Based on assertion for supported element types in OMPIRBuilder.cpp
146 // createAtomicRead
147 mlir::Type unwrappedEleTy = fir::unwrapRefType(elementType);
148 bool supportedAtomicType =
149 (!fir::isa_complex(unwrappedEleTy) && fir::isa_trivial(unwrappedEleTy));
150 if (!supportedAtomicType)
151 TODO(loc, "Unsupported atomic type");
152 }
153 }
154
155 /// Used to generate atomic.read operation which is created in existing
156 /// location set by builder.
157 template <typename AtomicListT>
158 static inline void genOmpAccAtomicCaptureStatement(
159 Fortran::lower::AbstractConverter &converter, mlir::Value fromAddress,
160 mlir::Value toAddress,
161 [[maybe_unused]] const AtomicListT *leftHandClauseList,
162 [[maybe_unused]] const AtomicListT *rightHandClauseList,
163 mlir::Type elementType, mlir::Location loc) {
164 // Generate `atomic.read` operation for atomic assigment statements
165 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
166
167 processOmpAtomicTODO<AtomicListT>(elementType, loc);
168
169 if constexpr (std::is_same<AtomicListT,
170 Fortran::parser::OmpAtomicClauseList>()) {
171 // If no hint clause is specified, the effect is as if
172 // hint(omp_sync_hint_none) had been specified.
173 mlir::IntegerAttr hint = nullptr;
174
175 mlir::omp::ClauseMemoryOrderKindAttr memoryOrder = nullptr;
176 if (leftHandClauseList)
177 genOmpAtomicHintAndMemoryOrderClauses(converter, *leftHandClauseList,
178 hint, memoryOrder);
179 if (rightHandClauseList)
180 genOmpAtomicHintAndMemoryOrderClauses(converter, *rightHandClauseList,
181 hint, memoryOrder);
182 firOpBuilder.create<mlir::omp::AtomicReadOp>(
183 loc, fromAddress, toAddress, mlir::TypeAttr::get(elementType), hint,
184 memoryOrder);
185 } else {
186 firOpBuilder.create<mlir::acc::AtomicReadOp>(
187 loc, fromAddress, toAddress, mlir::TypeAttr::get(elementType));
188 }
189 }
190
191 /// Used to generate atomic.write operation which is created in existing
192 /// location set by builder.
193 template <typename AtomicListT>
194 static inline void genOmpAccAtomicWriteStatement(
195 Fortran::lower::AbstractConverter &converter, mlir::Value lhsAddr,
196 mlir::Value rhsExpr, [[maybe_unused]] const AtomicListT *leftHandClauseList,
197 [[maybe_unused]] const AtomicListT *rightHandClauseList, mlir::Location loc,
198 mlir::Value *evaluatedExprValue = nullptr) {
199 // Generate `atomic.write` operation for atomic assignment statements
200 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
201
202 mlir::Type varType = fir::unwrapRefType(lhsAddr.getType());
203 rhsExpr = firOpBuilder.createConvert(loc, varType, rhsExpr);
204
205 processOmpAtomicTODO<AtomicListT>(varType, loc);
206
207 if constexpr (std::is_same<AtomicListT,
208 Fortran::parser::OmpAtomicClauseList>()) {
209 // If no hint clause is specified, the effect is as if
210 // hint(omp_sync_hint_none) had been specified.
211 mlir::IntegerAttr hint = nullptr;
212 mlir::omp::ClauseMemoryOrderKindAttr memoryOrder = nullptr;
213 if (leftHandClauseList)
214 genOmpAtomicHintAndMemoryOrderClauses(converter, *leftHandClauseList,
215 hint, memoryOrder);
216 if (rightHandClauseList)
217 genOmpAtomicHintAndMemoryOrderClauses(converter, *rightHandClauseList,
218 hint, memoryOrder);
219 firOpBuilder.create<mlir::omp::AtomicWriteOp>(loc, lhsAddr, rhsExpr, hint,
220 memoryOrder);
221 } else {
222 firOpBuilder.create<mlir::acc::AtomicWriteOp>(loc, lhsAddr, rhsExpr);
223 }
224 }
225
226 /// Used to generate atomic.update operation which is created in existing
227 /// location set by builder.
228 template <typename AtomicListT>
229 static inline void genOmpAccAtomicUpdateStatement(
230 Fortran::lower::AbstractConverter &converter, mlir::Value lhsAddr,
231 mlir::Type varType, const Fortran::parser::Variable &assignmentStmtVariable,
232 const Fortran::parser::Expr &assignmentStmtExpr,
233 [[maybe_unused]] const AtomicListT *leftHandClauseList,
234 [[maybe_unused]] const AtomicListT *rightHandClauseList, mlir::Location loc,
235 mlir::Operation *atomicCaptureOp = nullptr) {
236 // Generate `atomic.update` operation for atomic assignment statements
237 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
238 mlir::Location currentLocation = converter.getCurrentLocation();
239
240 // Create the omp.atomic.update or acc.atomic.update operation
241 //
242 // func.func @_QPsb() {
243 // %0 = fir.alloca i32 {bindc_name = "a", uniq_name = "_QFsbEa"}
244 // %1 = fir.alloca i32 {bindc_name = "b", uniq_name = "_QFsbEb"}
245 // %2 = fir.load %1 : !fir.ref<i32>
246 // omp.atomic.update %0 : !fir.ref<i32> {
247 // ^bb0(%arg0: i32):
248 // %3 = arith.addi %arg0, %2 : i32
249 // omp.yield(%3 : i32)
250 // }
251 // return
252 // }
253
254 auto getArgExpression =
255 [](std::list<parser::ActualArgSpec>::const_iterator it) {
256 const auto &arg{std::get<parser::ActualArg>((*it).t)};
257 const auto *parserExpr{
258 std::get_if<common::Indirection<parser::Expr>>(&arg.u)};
259 return parserExpr;
260 };
261
262 // Lower any non atomic sub-expression before the atomic operation, and
263 // map its lowered value to the semantic representation.
264 Fortran::lower::ExprToValueMap exprValueOverrides;
265 // Max and min intrinsics can have a list of Args. Hence we need a list
266 // of nonAtomicSubExprs to hoist. Currently, only the load is hoisted.
267 llvm::SmallVector<const Fortran::lower::SomeExpr *> nonAtomicSubExprs;
268 Fortran::common::visit(
269 Fortran::common::visitors{
270 [&](const common::Indirection<parser::FunctionReference> &funcRef)
271 -> void {
272 const auto &args{std::get<std::list<parser::ActualArgSpec>>(
273 funcRef.value().v.t)};
274 std::list<parser::ActualArgSpec>::const_iterator beginIt =
275 args.begin();
276 std::list<parser::ActualArgSpec>::const_iterator endIt = args.end();
277 const auto *exprFirst{getArgExpression(beginIt)};
278 if (exprFirst && exprFirst->value().source ==
279 assignmentStmtVariable.GetSource()) {
280 // Add everything except the first
281 beginIt++;
282 } else {
283 // Add everything except the last
284 endIt--;
285 }
286 std::list<parser::ActualArgSpec>::const_iterator it;
287 for (it = beginIt; it != endIt; it++) {
288 const common::Indirection<parser::Expr> *expr =
289 getArgExpression(it);
290 if (expr)
291 nonAtomicSubExprs.push_back(Fortran::semantics::GetExpr(*expr));
292 }
293 },
294 [&](const auto &op) -> void {
295 using T = std::decay_t<decltype(op)>;
296 if constexpr (std::is_base_of<
297 Fortran::parser::Expr::IntrinsicBinary,
298 T>::value) {
299 const auto &exprLeft{std::get<0>(op.t)};
300 const auto &exprRight{std::get<1>(op.t)};
301 if (exprLeft.value().source == assignmentStmtVariable.GetSource())
302 nonAtomicSubExprs.push_back(
303 Fortran::semantics::GetExpr(exprRight));
304 else
305 nonAtomicSubExprs.push_back(
306 Fortran::semantics::GetExpr(exprLeft));
307 }
308 },
309 },
310 assignmentStmtExpr.u);
311 StatementContext nonAtomicStmtCtx;
312 if (!nonAtomicSubExprs.empty()) {
313 // Generate non atomic part before all the atomic operations.
314 auto insertionPoint = firOpBuilder.saveInsertionPoint();
315 if (atomicCaptureOp)
316 firOpBuilder.setInsertionPoint(atomicCaptureOp);
317 mlir::Value nonAtomicVal;
318 for (auto *nonAtomicSubExpr : nonAtomicSubExprs) {
319 nonAtomicVal = fir::getBase(converter.genExprValue(
320 currentLocation, *nonAtomicSubExpr, nonAtomicStmtCtx));
321 exprValueOverrides.try_emplace(nonAtomicSubExpr, nonAtomicVal);
322 }
323 if (atomicCaptureOp)
324 firOpBuilder.restoreInsertionPoint(insertionPoint);
325 }
326
327 mlir::Operation *atomicUpdateOp = nullptr;
328 if constexpr (std::is_same<AtomicListT,
329 Fortran::parser::OmpAtomicClauseList>()) {
330 // If no hint clause is specified, the effect is as if
331 // hint(omp_sync_hint_none) had been specified.
332 mlir::IntegerAttr hint = nullptr;
333 mlir::omp::ClauseMemoryOrderKindAttr memoryOrder = nullptr;
334 if (leftHandClauseList)
335 genOmpAtomicHintAndMemoryOrderClauses(converter, *leftHandClauseList,
336 hint, memoryOrder);
337 if (rightHandClauseList)
338 genOmpAtomicHintAndMemoryOrderClauses(converter, *rightHandClauseList,
339 hint, memoryOrder);
340 atomicUpdateOp = firOpBuilder.create<mlir::omp::AtomicUpdateOp>(
341 currentLocation, lhsAddr, hint, memoryOrder);
342 } else {
343 atomicUpdateOp = firOpBuilder.create<mlir::acc::AtomicUpdateOp>(
344 currentLocation, lhsAddr);
345 }
346
347 processOmpAtomicTODO<AtomicListT>(varType, loc);
348
349 llvm::SmallVector<mlir::Type> varTys = {varType};
350 llvm::SmallVector<mlir::Location> locs = {currentLocation};
351 firOpBuilder.createBlock(&atomicUpdateOp->getRegion(0), {}, varTys, locs);
352 mlir::Value val =
353 fir::getBase(atomicUpdateOp->getRegion(0).front().getArgument(0));
354
355 exprValueOverrides.try_emplace(
356 Fortran::semantics::GetExpr(assignmentStmtVariable), val);
357 {
358 // statement context inside the atomic block.
359 converter.overrideExprValues(&exprValueOverrides);
360 Fortran::lower::StatementContext atomicStmtCtx;
361 mlir::Value rhsExpr = fir::getBase(converter.genExprValue(
362 *Fortran::semantics::GetExpr(assignmentStmtExpr), atomicStmtCtx));
363 mlir::Value convertResult =
364 firOpBuilder.createConvert(currentLocation, varType, rhsExpr);
365 if constexpr (std::is_same<AtomicListT,
366 Fortran::parser::OmpAtomicClauseList>()) {
367 firOpBuilder.create<mlir::omp::YieldOp>(currentLocation, convertResult);
368 } else {
369 firOpBuilder.create<mlir::acc::YieldOp>(currentLocation, convertResult);
370 }
371 converter.resetExprOverrides();
372 }
373 firOpBuilder.setInsertionPointAfter(atomicUpdateOp);
374 }
375
376 /// Processes an atomic construct with write clause.
377 template <typename AtomicT, typename AtomicListT>
378 void genOmpAccAtomicWrite(Fortran::lower::AbstractConverter &converter,
379 const AtomicT &atomicWrite, mlir::Location loc) {
380 const AtomicListT *rightHandClauseList = nullptr;
381 const AtomicListT *leftHandClauseList = nullptr;
382 if constexpr (std::is_same<AtomicListT,
383 Fortran::parser::OmpAtomicClauseList>()) {
384 // Get the address of atomic read operands.
385 rightHandClauseList = &std::get<2>(atomicWrite.t);
386 leftHandClauseList = &std::get<0>(atomicWrite.t);
387 }
388
389 const Fortran::parser::AssignmentStmt &stmt =
390 std::get<Fortran::parser::Statement<Fortran::parser::AssignmentStmt>>(
391 atomicWrite.t)
392 .statement;
393 const Fortran::evaluate::Assignment &assign = *stmt.typedAssignment->v;
394 Fortran::lower::StatementContext stmtCtx;
395 // Get the value and address of atomic write operands.
396 mlir::Value rhsExpr =
397 fir::getBase(converter.genExprValue(assign.rhs, stmtCtx));
398 mlir::Value lhsAddr =
399 fir::getBase(converter.genExprAddr(assign.lhs, stmtCtx));
400 genOmpAccAtomicWriteStatement(converter, lhsAddr, rhsExpr, leftHandClauseList,
401 rightHandClauseList, loc);
402 }
403
404 /// Processes an atomic construct with read clause.
405 template <typename AtomicT, typename AtomicListT>
406 void genOmpAccAtomicRead(Fortran::lower::AbstractConverter &converter,
407 const AtomicT &atomicRead, mlir::Location loc) {
408 const AtomicListT *rightHandClauseList = nullptr;
409 const AtomicListT *leftHandClauseList = nullptr;
410 if constexpr (std::is_same<AtomicListT,
411 Fortran::parser::OmpAtomicClauseList>()) {
412 // Get the address of atomic read operands.
413 rightHandClauseList = &std::get<2>(atomicRead.t);
414 leftHandClauseList = &std::get<0>(atomicRead.t);
415 }
416
417 const auto &assignmentStmtExpr = std::get<Fortran::parser::Expr>(
418 std::get<Fortran::parser::Statement<Fortran::parser::AssignmentStmt>>(
419 atomicRead.t)
420 .statement.t);
421 const auto &assignmentStmtVariable = std::get<Fortran::parser::Variable>(
422 std::get<Fortran::parser::Statement<Fortran::parser::AssignmentStmt>>(
423 atomicRead.t)
424 .statement.t);
425
426 Fortran::lower::StatementContext stmtCtx;
427 const Fortran::semantics::SomeExpr &fromExpr =
428 *Fortran::semantics::GetExpr(assignmentStmtExpr);
429 mlir::Type elementType = converter.genType(fromExpr);
430 mlir::Value fromAddress =
431 fir::getBase(converter.genExprAddr(fromExpr, stmtCtx));
432 mlir::Value toAddress = fir::getBase(converter.genExprAddr(
433 *Fortran::semantics::GetExpr(assignmentStmtVariable), stmtCtx));
434 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
435 if (fromAddress.getType() != toAddress.getType())
436 fromAddress =
437 builder.create<fir::ConvertOp>(loc, toAddress.getType(), fromAddress);
438 genOmpAccAtomicCaptureStatement(converter, fromAddress, toAddress,
439 leftHandClauseList, rightHandClauseList,
440 elementType, loc);
441 }
442
443 /// Processes an atomic construct with update clause.
444 template <typename AtomicT, typename AtomicListT>
445 void genOmpAccAtomicUpdate(Fortran::lower::AbstractConverter &converter,
446 const AtomicT &atomicUpdate, mlir::Location loc) {
447 const AtomicListT *rightHandClauseList = nullptr;
448 const AtomicListT *leftHandClauseList = nullptr;
449 if constexpr (std::is_same<AtomicListT,
450 Fortran::parser::OmpAtomicClauseList>()) {
451 // Get the address of atomic read operands.
452 rightHandClauseList = &std::get<2>(atomicUpdate.t);
453 leftHandClauseList = &std::get<0>(atomicUpdate.t);
454 }
455
456 const auto &assignmentStmtExpr = std::get<Fortran::parser::Expr>(
457 std::get<Fortran::parser::Statement<Fortran::parser::AssignmentStmt>>(
458 atomicUpdate.t)
459 .statement.t);
460 const auto &assignmentStmtVariable = std::get<Fortran::parser::Variable>(
461 std::get<Fortran::parser::Statement<Fortran::parser::AssignmentStmt>>(
462 atomicUpdate.t)
463 .statement.t);
464
465 Fortran::lower::StatementContext stmtCtx;
466 mlir::Value lhsAddr = fir::getBase(converter.genExprAddr(
467 *Fortran::semantics::GetExpr(assignmentStmtVariable), stmtCtx));
468 mlir::Type varType = fir::unwrapRefType(lhsAddr.getType());
469 genOmpAccAtomicUpdateStatement<AtomicListT>(
470 converter, lhsAddr, varType, assignmentStmtVariable, assignmentStmtExpr,
471 leftHandClauseList, rightHandClauseList, loc);
472 }
473
474 /// Processes an atomic construct with no clause - which implies update clause.
475 template <typename AtomicT, typename AtomicListT>
476 void genOmpAtomic(Fortran::lower::AbstractConverter &converter,
477 const AtomicT &atomicConstruct, mlir::Location loc) {
478 const AtomicListT &atomicClauseList =
479 std::get<AtomicListT>(atomicConstruct.t);
480 const auto &assignmentStmtExpr = std::get<Fortran::parser::Expr>(
481 std::get<Fortran::parser::Statement<Fortran::parser::AssignmentStmt>>(
482 atomicConstruct.t)
483 .statement.t);
484 const auto &assignmentStmtVariable = std::get<Fortran::parser::Variable>(
485 std::get<Fortran::parser::Statement<Fortran::parser::AssignmentStmt>>(
486 atomicConstruct.t)
487 .statement.t);
488 Fortran::lower::StatementContext stmtCtx;
489 mlir::Value lhsAddr = fir::getBase(converter.genExprAddr(
490 *Fortran::semantics::GetExpr(assignmentStmtVariable), stmtCtx));
491 mlir::Type varType = fir::unwrapRefType(lhsAddr.getType());
492 // If atomic-clause is not present on the construct, the behaviour is as if
493 // the update clause is specified (for both OpenMP and OpenACC).
494 genOmpAccAtomicUpdateStatement<AtomicListT>(
495 converter, lhsAddr, varType, assignmentStmtVariable, assignmentStmtExpr,
496 &atomicClauseList, nullptr, loc);
497 }
498
499 /// Processes an atomic construct with capture clause.
500 template <typename AtomicT, typename AtomicListT>
501 void genOmpAccAtomicCapture(Fortran::lower::AbstractConverter &converter,
502 const AtomicT &atomicCapture, mlir::Location loc) {
503 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
504
505 const Fortran::parser::AssignmentStmt &stmt1 =
506 std::get<typename AtomicT::Stmt1>(atomicCapture.t).v.statement;
507 const Fortran::evaluate::Assignment &assign1 = *stmt1.typedAssignment->v;
508 const auto &stmt1Var{std::get<Fortran::parser::Variable>(stmt1.t)};
509 const auto &stmt1Expr{std::get<Fortran::parser::Expr>(stmt1.t)};
510 const Fortran::parser::AssignmentStmt &stmt2 =
511 std::get<typename AtomicT::Stmt2>(atomicCapture.t).v.statement;
512 const Fortran::evaluate::Assignment &assign2 = *stmt2.typedAssignment->v;
513 const auto &stmt2Var{std::get<Fortran::parser::Variable>(stmt2.t)};
514 const auto &stmt2Expr{std::get<Fortran::parser::Expr>(stmt2.t)};
515
516 // Pre-evaluate expressions to be used in the various operations inside
517 // `atomic.capture` since it is not desirable to have anything other than
518 // a `atomic.read`, `atomic.write`, or `atomic.update` operation
519 // inside `atomic.capture`
520 Fortran::lower::StatementContext stmtCtx;
521 mlir::Value stmt1LHSArg, stmt1RHSArg, stmt2LHSArg, stmt2RHSArg;
522 mlir::Type elementType;
523 // LHS evaluations are common to all combinations of `atomic.capture`
524 stmt1LHSArg = fir::getBase(converter.genExprAddr(assign1.lhs, stmtCtx));
525 stmt2LHSArg = fir::getBase(converter.genExprAddr(assign2.lhs, stmtCtx));
526
527 // Operation specific RHS evaluations
528 if (checkForSingleVariableOnRHS(stmt1)) {
529 // Atomic capture construct is of the form [capture-stmt, update-stmt] or
530 // of the form [capture-stmt, write-stmt]
531 stmt1RHSArg = fir::getBase(converter.genExprAddr(assign1.rhs, stmtCtx));
532 stmt2RHSArg = fir::getBase(converter.genExprValue(assign2.rhs, stmtCtx));
533 } else {
534 // Atomic capture construct is of the form [update-stmt, capture-stmt]
535 stmt1RHSArg = fir::getBase(converter.genExprValue(assign1.rhs, stmtCtx));
536 stmt2RHSArg = fir::getBase(converter.genExprAddr(assign2.lhs, stmtCtx));
537 }
538 // Type information used in generation of `atomic.update` operation
539 mlir::Type stmt1VarType =
540 fir::getBase(converter.genExprValue(assign1.lhs, stmtCtx)).getType();
541 mlir::Type stmt2VarType =
542 fir::getBase(converter.genExprValue(assign2.lhs, stmtCtx)).getType();
543
544 mlir::Operation *atomicCaptureOp = nullptr;
545 if constexpr (std::is_same<AtomicListT,
546 Fortran::parser::OmpAtomicClauseList>()) {
547 mlir::IntegerAttr hint = nullptr;
548 mlir::omp::ClauseMemoryOrderKindAttr memoryOrder = nullptr;
549 const AtomicListT &rightHandClauseList = std::get<2>(atomicCapture.t);
550 const AtomicListT &leftHandClauseList = std::get<0>(atomicCapture.t);
551 genOmpAtomicHintAndMemoryOrderClauses(converter, leftHandClauseList, hint,
552 memoryOrder);
553 genOmpAtomicHintAndMemoryOrderClauses(converter, rightHandClauseList, hint,
554 memoryOrder);
555 atomicCaptureOp =
556 firOpBuilder.create<mlir::omp::AtomicCaptureOp>(loc, hint, memoryOrder);
557 } else {
558 atomicCaptureOp = firOpBuilder.create<mlir::acc::AtomicCaptureOp>(loc);
559 }
560
561 firOpBuilder.createBlock(&(atomicCaptureOp->getRegion(0)));
562 mlir::Block &block = atomicCaptureOp->getRegion(0).back();
563 firOpBuilder.setInsertionPointToStart(&block);
564 if (checkForSingleVariableOnRHS(stmt1)) {
565 if (checkForSymbolMatch(stmt2)) {
566 // Atomic capture construct is of the form [capture-stmt, update-stmt]
567 const Fortran::semantics::SomeExpr &fromExpr =
568 *Fortran::semantics::GetExpr(stmt1Expr);
569 elementType = converter.genType(fromExpr);
570 genOmpAccAtomicCaptureStatement<AtomicListT>(
571 converter, stmt1RHSArg, stmt1LHSArg,
572 /*leftHandClauseList=*/nullptr,
573 /*rightHandClauseList=*/nullptr, elementType, loc);
574 genOmpAccAtomicUpdateStatement<AtomicListT>(
575 converter, stmt1RHSArg, stmt2VarType, stmt2Var, stmt2Expr,
576 /*leftHandClauseList=*/nullptr,
577 /*rightHandClauseList=*/nullptr, loc, atomicCaptureOp);
578 } else {
579 // Atomic capture construct is of the form [capture-stmt, write-stmt]
580 const Fortran::semantics::SomeExpr &fromExpr =
581 *Fortran::semantics::GetExpr(stmt1Expr);
582 elementType = converter.genType(fromExpr);
583 genOmpAccAtomicCaptureStatement<AtomicListT>(
584 converter, stmt1RHSArg, stmt1LHSArg,
585 /*leftHandClauseList=*/nullptr,
586 /*rightHandClauseList=*/nullptr, elementType, loc);
587 genOmpAccAtomicWriteStatement<AtomicListT>(
588 converter, stmt1RHSArg, stmt2RHSArg,
589 /*leftHandClauseList=*/nullptr,
590 /*rightHandClauseList=*/nullptr, loc);
591 }
592 } else {
593 // Atomic capture construct is of the form [update-stmt, capture-stmt]
594 firOpBuilder.setInsertionPointToEnd(&block);
595 const Fortran::semantics::SomeExpr &fromExpr =
596 *Fortran::semantics::GetExpr(stmt2Expr);
597 elementType = converter.genType(fromExpr);
598 genOmpAccAtomicCaptureStatement<AtomicListT>(
599 converter, stmt1LHSArg, stmt2LHSArg,
600 /*leftHandClauseList=*/nullptr,
601 /*rightHandClauseList=*/nullptr, elementType, loc);
602 firOpBuilder.setInsertionPointToStart(&block);
603 genOmpAccAtomicUpdateStatement<AtomicListT>(
604 converter, stmt1LHSArg, stmt1VarType, stmt1Var, stmt1Expr,
605 /*leftHandClauseList=*/nullptr,
606 /*rightHandClauseList=*/nullptr, loc, atomicCaptureOp);
607 }
608 firOpBuilder.setInsertionPointToEnd(&block);
609 if constexpr (std::is_same<AtomicListT,
610 Fortran::parser::OmpAtomicClauseList>()) {
611 firOpBuilder.create<mlir::omp::TerminatorOp>(loc);
612 } else {
613 firOpBuilder.create<mlir::acc::TerminatorOp>(loc);
614 }
615 firOpBuilder.setInsertionPointToStart(&block);
616 }
617
618 /// Create empty blocks for the current region.
619 /// These blocks replace blocks parented to an enclosing region.
620 template <typename... TerminatorOps>
621 void createEmptyRegionBlocks(
622 fir::FirOpBuilder &builder,
623 std::list<Fortran::lower::pft::Evaluation> &evaluationList) {
624 mlir::Region *region = &builder.getRegion();
625 for (Fortran::lower::pft::Evaluation &eval : evaluationList) {
626 if (eval.block) {
627 if (eval.block->empty()) {
628 eval.block->erase();
629 eval.block = builder.createBlock(region);
630 } else {
631 [[maybe_unused]] mlir::Operation &terminatorOp = eval.block->back();
632 assert(mlir::isa<TerminatorOps...>(terminatorOp) &&
633 "expected terminator op");
634 }
635 }
636 if (!eval.isDirective() && eval.hasNestedEvaluations())
637 createEmptyRegionBlocks<TerminatorOps...>(builder,
638 eval.getNestedEvaluations());
639 }
640 }
641
642 inline AddrAndBoundsInfo
643 getDataOperandBaseAddr(Fortran::lower::AbstractConverter &converter,
644 fir::FirOpBuilder &builder,
645 Fortran::lower::SymbolRef sym, mlir::Location loc) {
646 mlir::Value symAddr = converter.getSymbolAddress(sym);
647 mlir::Value rawInput = symAddr;
648 if (auto declareOp =
649 mlir::dyn_cast_or_null<hlfir::DeclareOp>(symAddr.getDefiningOp())) {
650 symAddr = declareOp.getResults()[0];
651 rawInput = declareOp.getResults()[1];
652 }
653
654 // TODO: Might need revisiting to handle for non-shared clauses
655 if (!symAddr) {
656 if (const auto *details =
657 sym->detailsIf<Fortran::semantics::HostAssocDetails>()) {
658 symAddr = converter.getSymbolAddress(details->symbol());
659 rawInput = symAddr;
660 }
661 }
662
663 if (!symAddr)
664 llvm::report_fatal_error("could not retrieve symbol address");
665
666 mlir::Value isPresent;
667 if (Fortran::semantics::IsOptional(sym))
668 isPresent =
669 builder.create<fir::IsPresentOp>(loc, builder.getI1Type(), rawInput);
670
671 if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(
672 fir::unwrapRefType(symAddr.getType()))) {
673 if (mlir::isa<fir::RecordType>(boxTy.getEleTy()))
674 TODO(loc, "derived type");
675
676 // Load the box when baseAddr is a `fir.ref<fir.box<T>>` or a
677 // `fir.ref<fir.class<T>>` type.
678 if (mlir::isa<fir::ReferenceType>(symAddr.getType())) {
679 if (Fortran::semantics::IsOptional(sym)) {
680 mlir::Value addr =
681 builder.genIfOp(loc, {boxTy}, isPresent, /*withElseRegion=*/true)
682 .genThen([&]() {
683 mlir::Value load = builder.create<fir::LoadOp>(loc, symAddr);
684 builder.create<fir::ResultOp>(loc, mlir::ValueRange{load});
685 })
686 .genElse([&] {
687 mlir::Value absent =
688 builder.create<fir::AbsentOp>(loc, boxTy);
689 builder.create<fir::ResultOp>(loc, mlir::ValueRange{absent});
690 })
691 .getResults()[0];
692 return AddrAndBoundsInfo(addr, rawInput, isPresent);
693 }
694 mlir::Value addr = builder.create<fir::LoadOp>(loc, symAddr);
695 return AddrAndBoundsInfo(addr, rawInput, isPresent);
696 }
697 }
698 return AddrAndBoundsInfo(symAddr, rawInput, isPresent);
699 }
700
701 template <typename BoundsOp, typename BoundsType>
702 llvm::SmallVector<mlir::Value>
703 gatherBoundsOrBoundValues(fir::FirOpBuilder &builder, mlir::Location loc,
704 fir::ExtendedValue dataExv, mlir::Value box,
705 bool collectValuesOnly = false) {
706 llvm::SmallVector<mlir::Value> values;
707 mlir::Value byteStride;
708 mlir::Type idxTy = builder.getIndexType();
709 mlir::Type boundTy = builder.getType<BoundsType>();
710 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
711 for (unsigned dim = 0; dim < dataExv.rank(); ++dim) {
712 mlir::Value d = builder.createIntegerConstant(loc, idxTy, dim);
713 mlir::Value baseLb =
714 fir::factory::readLowerBound(builder, loc, dataExv, dim, one);
715 auto dimInfo =
716 builder.create<fir::BoxDimsOp>(loc, idxTy, idxTy, idxTy, box, d);
717 mlir::Value lb = builder.createIntegerConstant(loc, idxTy, 0);
718 mlir::Value ub =
719 builder.create<mlir::arith::SubIOp>(loc, dimInfo.getExtent(), one);
720 if (dim == 0) // First stride is the element size.
721 byteStride = dimInfo.getByteStride();
722 if (collectValuesOnly) {
723 values.push_back(lb);
724 values.push_back(ub);
725 values.push_back(dimInfo.getExtent());
726 values.push_back(byteStride);
727 values.push_back(baseLb);
728 } else {
729 mlir::Value bound = builder.create<BoundsOp>(
730 loc, boundTy, lb, ub, dimInfo.getExtent(), byteStride, true, baseLb);
731 values.push_back(bound);
732 }
733 // Compute the stride for the next dimension.
734 byteStride = builder.create<mlir::arith::MulIOp>(loc, byteStride,
735 dimInfo.getExtent());
736 }
737 return values;
738 }
739
740 /// Generate the bounds operation from the descriptor information.
741 template <typename BoundsOp, typename BoundsType>
742 llvm::SmallVector<mlir::Value>
743 genBoundsOpsFromBox(fir::FirOpBuilder &builder, mlir::Location loc,
744 fir::ExtendedValue dataExv,
745 Fortran::lower::AddrAndBoundsInfo &info) {
746 llvm::SmallVector<mlir::Value> bounds;
747 mlir::Type idxTy = builder.getIndexType();
748 mlir::Type boundTy = builder.getType<BoundsType>();
749
750 assert(mlir::isa<fir::BaseBoxType>(info.addr.getType()) &&
751 "expect fir.box or fir.class");
752
753 if (info.isPresent) {
754 llvm::SmallVector<mlir::Type> resTypes;
755 constexpr unsigned nbValuesPerBound = 5;
756 for (unsigned dim = 0; dim < dataExv.rank() * nbValuesPerBound; ++dim)
757 resTypes.push_back(idxTy);
758
759 mlir::Operation::result_range ifRes =
760 builder.genIfOp(loc, resTypes, info.isPresent, /*withElseRegion=*/true)
761 .genThen([&]() {
762 llvm::SmallVector<mlir::Value> boundValues =
763 gatherBoundsOrBoundValues<BoundsOp, BoundsType>(
764 builder, loc, dataExv, info.addr,
765 /*collectValuesOnly=*/true);
766 builder.create<fir::ResultOp>(loc, boundValues);
767 })
768 .genElse([&] {
769 // Box is not present. Populate bound values with default values.
770 llvm::SmallVector<mlir::Value> boundValues;
771 mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0);
772 mlir::Value mOne = builder.createMinusOneInteger(loc, idxTy);
773 for (unsigned dim = 0; dim < dataExv.rank(); ++dim) {
774 boundValues.push_back(zero); // lb
775 boundValues.push_back(mOne); // ub
776 boundValues.push_back(zero); // extent
777 boundValues.push_back(zero); // byteStride
778 boundValues.push_back(zero); // baseLb
779 }
780 builder.create<fir::ResultOp>(loc, boundValues);
781 })
782 .getResults();
783 // Create the bound operations outside the if-then-else with the if op
784 // results.
785 for (unsigned i = 0; i < ifRes.size(); i += nbValuesPerBound) {
786 mlir::Value bound = builder.create<BoundsOp>(
787 loc, boundTy, ifRes[i], ifRes[i + 1], ifRes[i + 2], ifRes[i + 3],
788 true, ifRes[i + 4]);
789 bounds.push_back(bound);
790 }
791 } else {
792 bounds = gatherBoundsOrBoundValues<BoundsOp, BoundsType>(
793 builder, loc, dataExv, info.addr);
794 }
795 return bounds;
796 }
797
798 /// Generate bounds operation for base array without any subscripts
799 /// provided.
800 template <typename BoundsOp, typename BoundsType>
801 llvm::SmallVector<mlir::Value>
802 genBaseBoundsOps(fir::FirOpBuilder &builder, mlir::Location loc,
803 fir::ExtendedValue dataExv, bool isAssumedSize) {
804 mlir::Type idxTy = builder.getIndexType();
805 mlir::Type boundTy = builder.getType<BoundsType>();
806 llvm::SmallVector<mlir::Value> bounds;
807
808 if (dataExv.rank() == 0)
809 return bounds;
810
811 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
812 const unsigned rank = dataExv.rank();
813 for (unsigned dim = 0; dim < rank; ++dim) {
814 mlir::Value baseLb =
815 fir::factory::readLowerBound(builder, loc, dataExv, dim, one);
816 mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0);
817 mlir::Value ub;
818 mlir::Value lb = zero;
819 mlir::Value ext = fir::factory::readExtent(builder, loc, dataExv, dim);
820 if (isAssumedSize && dim + 1 == rank) {
821 ext = zero;
822 ub = lb;
823 } else {
824 // ub = extent - 1
825 ub = builder.create<mlir::arith::SubIOp>(loc, ext, one);
826 }
827
828 mlir::Value bound =
829 builder.create<BoundsOp>(loc, boundTy, lb, ub, ext, one, false, baseLb);
830 bounds.push_back(bound);
831 }
832 return bounds;
833 }
834
835 namespace detail {
836 template <typename T> //
837 static T &&AsRvalueRef(T &&t) {
838 return std::move(t);
839 }
840 template <typename T> //
841 static T AsRvalueRef(T &t) {
842 return t;
843 }
844 template <typename T> //
845 static T AsRvalueRef(const T &t) {
846 return t;
847 }
848
849 // Helper class for stripping enclosing parentheses and a conversion that
850 // preserves type category. This is used for triplet elements, which are
851 // always of type integer(kind=8). The lower/upper bounds are converted to
852 // an "index" type, which is 64-bit, so the explicit conversion to kind=8
853 // (if present) is not needed. When it's present, though, it causes generated
854 // names to contain "int(..., kind=8)".
855 struct PeelConvert {
856 template <Fortran::common::TypeCategory Category, int Kind>
857 static Fortran::semantics::MaybeExpr visit_with_category(
858 const Fortran::evaluate::Expr<Fortran::evaluate::Type<Category, Kind>>
859 &expr) {
860 return Fortran::common::visit(
861 [](auto &&s) { return visit_with_category<Category, Kind>(s); },
862 expr.u);
863 }
864 template <Fortran::common::TypeCategory Category, int Kind>
865 static Fortran::semantics::MaybeExpr visit_with_category(
866 const Fortran::evaluate::Convert<Fortran::evaluate::Type<Category, Kind>,
867 Category> &expr) {
868 return AsGenericExpr(AsRvalueRef(expr.left()));
869 }
870 template <Fortran::common::TypeCategory Category, int Kind, typename T>
871 static Fortran::semantics::MaybeExpr visit_with_category(const T &) {
872 return std::nullopt; //
873 }
874 template <Fortran::common::TypeCategory Category, typename T>
875 static Fortran::semantics::MaybeExpr visit_with_category(const T &) {
876 return std::nullopt; //
877 }
878
879 template <Fortran::common::TypeCategory Category>
880 static Fortran::semantics::MaybeExpr
881 visit(const Fortran::evaluate::Expr<Fortran::evaluate::SomeKind<Category>>
882 &expr) {
883 return Fortran::common::visit(
884 [](auto &&s) { return visit_with_category<Category>(s); }, expr.u);
885 }
886 static Fortran::semantics::MaybeExpr
887 visit(const Fortran::evaluate::Expr<Fortran::evaluate::SomeType> &expr) {
888 return Fortran::common::visit([](auto &&s) { return visit(s); }, expr.u);
889 }
890 template <typename T> //
891 static Fortran::semantics::MaybeExpr visit(const T &) {
892 return std::nullopt;
893 }
894 };
895
896 static Fortran::semantics::SomeExpr
897 peelOuterConvert(Fortran::semantics::SomeExpr &expr) {
898 if (auto peeled = PeelConvert::visit(expr))
899 return *peeled;
900 return expr;
901 }
902 } // namespace detail
903
904 /// Generate bounds operations for an array section when subscripts are
905 /// provided.
906 template <typename BoundsOp, typename BoundsType>
907 llvm::SmallVector<mlir::Value>
908 genBoundsOps(fir::FirOpBuilder &builder, mlir::Location loc,
909 Fortran::lower::AbstractConverter &converter,
910 Fortran::lower::StatementContext &stmtCtx,
911 const std::vector<Fortran::evaluate::Subscript> &subscripts,
912 std::stringstream &asFortran, fir::ExtendedValue &dataExv,
913 bool dataExvIsAssumedSize, AddrAndBoundsInfo &info,
914 bool treatIndexAsSection = false) {
915 int dimension = 0;
916 mlir::Type idxTy = builder.getIndexType();
917 mlir::Type boundTy = builder.getType<BoundsType>();
918 llvm::SmallVector<mlir::Value> bounds;
919
920 mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0);
921 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
922 const int dataExvRank = static_cast<int>(dataExv.rank());
923 for (const auto &subscript : subscripts) {
924 const auto *triplet{std::get_if<Fortran::evaluate::Triplet>(&subscript.u)};
925 if (triplet || treatIndexAsSection) {
926 if (dimension != 0)
927 asFortran << ',';
928 mlir::Value lbound, ubound, extent;
929 std::optional<std::int64_t> lval, uval;
930 mlir::Value baseLb =
931 fir::factory::readLowerBound(builder, loc, dataExv, dimension, one);
932 bool defaultLb = baseLb == one;
933 mlir::Value stride = one;
934 bool strideInBytes = false;
935
936 if (mlir::isa<fir::BaseBoxType>(
937 fir::unwrapRefType(info.addr.getType()))) {
938 if (info.isPresent) {
939 stride =
940 builder
941 .genIfOp(loc, idxTy, info.isPresent, /*withElseRegion=*/true)
942 .genThen([&]() {
943 mlir::Value d =
944 builder.createIntegerConstant(loc, idxTy, dimension);
945 auto dimInfo = builder.create<fir::BoxDimsOp>(
946 loc, idxTy, idxTy, idxTy, info.addr, d);
947 builder.create<fir::ResultOp>(loc, dimInfo.getByteStride());
948 })
949 .genElse([&] {
950 mlir::Value zero =
951 builder.createIntegerConstant(loc, idxTy, 0);
952 builder.create<fir::ResultOp>(loc, zero);
953 })
954 .getResults()[0];
955 } else {
956 mlir::Value d = builder.createIntegerConstant(loc, idxTy, dimension);
957 auto dimInfo = builder.create<fir::BoxDimsOp>(loc, idxTy, idxTy,
958 idxTy, info.addr, d);
959 stride = dimInfo.getByteStride();
960 }
961 strideInBytes = true;
962 }
963
964 Fortran::semantics::MaybeExpr lower;
965 if (triplet) {
966 lower = Fortran::evaluate::AsGenericExpr(triplet->lower());
967 } else {
968 // Case of IndirectSubscriptIntegerExpr
969 using IndirectSubscriptIntegerExpr =
970 Fortran::evaluate::IndirectSubscriptIntegerExpr;
971 using SubscriptInteger = Fortran::evaluate::SubscriptInteger;
972 Fortran::evaluate::Expr<SubscriptInteger> oneInt =
973 std::get<IndirectSubscriptIntegerExpr>(subscript.u).value();
974 lower = Fortran::evaluate::AsGenericExpr(std::move(oneInt));
975 if (lower->Rank() > 0) {
976 mlir::emitError(
977 loc, "vector subscript cannot be used for an array section");
978 break;
979 }
980 }
981 if (lower) {
982 lval = Fortran::evaluate::ToInt64(*lower);
983 if (lval) {
984 if (defaultLb) {
985 lbound = builder.createIntegerConstant(loc, idxTy, *lval - 1);
986 } else {
987 mlir::Value lb = builder.createIntegerConstant(loc, idxTy, *lval);
988 lbound = builder.create<mlir::arith::SubIOp>(loc, lb, baseLb);
989 }
990 asFortran << *lval;
991 } else {
992 mlir::Value lb =
993 fir::getBase(converter.genExprValue(loc, *lower, stmtCtx));
994 lb = builder.createConvert(loc, baseLb.getType(), lb);
995 lbound = builder.create<mlir::arith::SubIOp>(loc, lb, baseLb);
996 asFortran << detail::peelOuterConvert(*lower).AsFortran();
997 }
998 } else {
999 // If the lower bound is not specified, then the section
1000 // starts from offset 0 of the dimension.
1001 // Note that the lowerbound in the BoundsOp is always 0-based.
1002 lbound = zero;
1003 }
1004
1005 if (!triplet) {
1006 // If it is a scalar subscript, then the upper bound
1007 // is equal to the lower bound, and the extent is one.
1008 ubound = lbound;
1009 extent = one;
1010 } else {
1011 asFortran << ':';
1012 Fortran::semantics::MaybeExpr upper =
1013 Fortran::evaluate::AsGenericExpr(triplet->upper());
1014
1015 if (upper) {
1016 uval = Fortran::evaluate::ToInt64(*upper);
1017 if (uval) {
1018 if (defaultLb) {
1019 ubound = builder.createIntegerConstant(loc, idxTy, *uval - 1);
1020 } else {
1021 mlir::Value ub = builder.createIntegerConstant(loc, idxTy, *uval);
1022 ubound = builder.create<mlir::arith::SubIOp>(loc, ub, baseLb);
1023 }
1024 asFortran << *uval;
1025 } else {
1026 mlir::Value ub =
1027 fir::getBase(converter.genExprValue(loc, *upper, stmtCtx));
1028 ub = builder.createConvert(loc, baseLb.getType(), ub);
1029 ubound = builder.create<mlir::arith::SubIOp>(loc, ub, baseLb);
1030 asFortran << detail::peelOuterConvert(*upper).AsFortran();
1031 }
1032 }
1033 if (lower && upper) {
1034 if (lval && uval && *uval < *lval) {
1035 mlir::emitError(loc, "zero sized array section");
1036 break;
1037 } else {
1038 // Stride is mandatory in evaluate::Triplet. Make sure it's 1.
1039 auto val = Fortran::evaluate::ToInt64(triplet->GetStride());
1040 if (!val || *val != 1) {
1041 mlir::emitError(loc, "stride cannot be specified on "
1042 "an array section");
1043 break;
1044 }
1045 }
1046 }
1047
1048 if (info.isPresent && mlir::isa<fir::BaseBoxType>(
1049 fir::unwrapRefType(info.addr.getType()))) {
1050 extent =
1051 builder
1052 .genIfOp(loc, idxTy, info.isPresent, /*withElseRegion=*/true)
1053 .genThen([&]() {
1054 mlir::Value ext = fir::factory::readExtent(
1055 builder, loc, dataExv, dimension);
1056 builder.create<fir::ResultOp>(loc, ext);
1057 })
1058 .genElse([&] {
1059 mlir::Value zero =
1060 builder.createIntegerConstant(loc, idxTy, 0);
1061 builder.create<fir::ResultOp>(loc, zero);
1062 })
1063 .getResults()[0];
1064 } else {
1065 extent = fir::factory::readExtent(builder, loc, dataExv, dimension);
1066 }
1067
1068 if (dataExvIsAssumedSize && dimension + 1 == dataExvRank) {
1069 extent = zero;
1070 if (ubound && lbound) {
1071 mlir::Value diff =
1072 builder.create<mlir::arith::SubIOp>(loc, ubound, lbound);
1073 extent = builder.create<mlir::arith::AddIOp>(loc, diff, one);
1074 }
1075 if (!ubound)
1076 ubound = lbound;
1077 }
1078
1079 if (!ubound) {
1080 // ub = extent - 1
1081 ubound = builder.create<mlir::arith::SubIOp>(loc, extent, one);
1082 }
1083 }
1084 mlir::Value bound = builder.create<BoundsOp>(
1085 loc, boundTy, lbound, ubound, extent, stride, strideInBytes, baseLb);
1086 bounds.push_back(bound);
1087 ++dimension;
1088 }
1089 }
1090 return bounds;
1091 }
1092
1093 namespace detail {
1094 template <typename Ref, typename Expr> //
1095 std::optional<Ref> getRef(Expr &&expr) {
1096 if constexpr (std::is_same_v<llvm::remove_cvref_t<Expr>,
1097 Fortran::evaluate::DataRef>) {
1098 if (auto *ref = std::get_if<Ref>(&expr.u))
1099 return *ref;
1100 return std::nullopt;
1101 } else {
1102 auto maybeRef = Fortran::evaluate::ExtractDataRef(expr);
1103 if (!maybeRef || !std::holds_alternative<Ref>(maybeRef->u))
1104 return std::nullopt;
1105 return std::get<Ref>(maybeRef->u);
1106 }
1107 }
1108 } // namespace detail
1109
1110 template <typename BoundsOp, typename BoundsType>
1111 AddrAndBoundsInfo gatherDataOperandAddrAndBounds(
1112 Fortran::lower::AbstractConverter &converter, fir::FirOpBuilder &builder,
1113 semantics::SemanticsContext &semaCtx,
1114 Fortran::lower::StatementContext &stmtCtx,
1115 Fortran::semantics::SymbolRef symbol,
1116 const Fortran::semantics::MaybeExpr &maybeDesignator,
1117 mlir::Location operandLocation, std::stringstream &asFortran,
1118 llvm::SmallVector<mlir::Value> &bounds, bool treatIndexAsSection = false) {
1119 using namespace Fortran;
1120
1121 AddrAndBoundsInfo info;
1122
1123 if (!maybeDesignator) {
1124 info = getDataOperandBaseAddr(converter, builder, symbol, operandLocation);
1125 asFortran << symbol->name().ToString();
1126 return info;
1127 }
1128
1129 semantics::SomeExpr designator = *maybeDesignator;
1130
1131 if ((designator.Rank() > 0 || treatIndexAsSection) &&
1132 IsArrayElement(designator)) {
1133 auto arrayRef = detail::getRef<evaluate::ArrayRef>(designator);
1134 // This shouldn't fail after IsArrayElement(designator).
1135 assert(arrayRef && "Expecting ArrayRef");
1136
1137 fir::ExtendedValue dataExv;
1138 bool dataExvIsAssumedSize = false;
1139
1140 auto toMaybeExpr = [&](auto &&base) {
1141 using BaseType = llvm::remove_cvref_t<decltype(base)>;
1142 evaluate::ExpressionAnalyzer ea{semaCtx};
1143
1144 if constexpr (std::is_same_v<evaluate::NamedEntity, BaseType>) {
1145 if (auto *ref = base.UnwrapSymbolRef())
1146 return ea.Designate(evaluate::DataRef{*ref});
1147 if (auto *ref = base.UnwrapComponent())
1148 return ea.Designate(evaluate::DataRef{*ref});
1149 llvm_unreachable("Unexpected NamedEntity");
1150 } else {
1151 static_assert(std::is_same_v<semantics::SymbolRef, BaseType>);
1152 return ea.Designate(evaluate::DataRef{base});
1153 }
1154 };
1155
1156 auto arrayBase = toMaybeExpr(arrayRef->base());
1157 assert(arrayBase);
1158
1159 if (detail::getRef<evaluate::Component>(*arrayBase)) {
1160 dataExv = converter.genExprAddr(operandLocation, *arrayBase, stmtCtx);
1161 info.addr = fir::getBase(dataExv);
1162 info.rawInput = info.addr;
1163 asFortran << arrayBase->AsFortran();
1164 } else {
1165 const semantics::Symbol &sym = arrayRef->GetLastSymbol();
1166 dataExvIsAssumedSize =
1167 Fortran::semantics::IsAssumedSizeArray(sym.GetUltimate());
1168 info = getDataOperandBaseAddr(converter, builder, sym, operandLocation);
1169 dataExv = converter.getSymbolExtendedValue(sym);
1170 asFortran << sym.name().ToString();
1171 }
1172
1173 if (!arrayRef->subscript().empty()) {
1174 asFortran << '(';
1175 bounds = genBoundsOps<BoundsOp, BoundsType>(
1176 builder, operandLocation, converter, stmtCtx, arrayRef->subscript(),
1177 asFortran, dataExv, dataExvIsAssumedSize, info, treatIndexAsSection);
1178 }
1179 asFortran << ')';
1180 } else if (auto compRef = detail::getRef<evaluate::Component>(designator)) {
1181 fir::ExtendedValue compExv =
1182 converter.genExprAddr(operandLocation, designator, stmtCtx);
1183 info.addr = fir::getBase(compExv);
1184 info.rawInput = info.addr;
1185 if (mlir::isa<fir::SequenceType>(fir::unwrapRefType(info.addr.getType())))
1186 bounds = genBaseBoundsOps<BoundsOp, BoundsType>(builder, operandLocation,
1187 compExv,
1188 /*isAssumedSize=*/false);
1189 asFortran << designator.AsFortran();
1190
1191 if (semantics::IsOptional(compRef->GetLastSymbol())) {
1192 info.isPresent = builder.create<fir::IsPresentOp>(
1193 operandLocation, builder.getI1Type(), info.rawInput);
1194 }
1195
1196 if (auto loadOp =
1197 mlir::dyn_cast_or_null<fir::LoadOp>(info.addr.getDefiningOp())) {
1198 if (fir::isAllocatableType(loadOp.getType()) ||
1199 fir::isPointerType(loadOp.getType()))
1200 info.addr = builder.create<fir::BoxAddrOp>(operandLocation, info.addr);
1201 info.rawInput = info.addr;
1202 }
1203
1204 // If the component is an allocatable or pointer the result of
1205 // genExprAddr will be the result of a fir.box_addr operation or
1206 // a fir.box_addr has been inserted just before.
1207 // Retrieve the box so we handle it like other descriptor.
1208 if (auto boxAddrOp =
1209 mlir::dyn_cast_or_null<fir::BoxAddrOp>(info.addr.getDefiningOp())) {
1210 info.addr = boxAddrOp.getVal();
1211 info.rawInput = info.addr;
1212 bounds = genBoundsOpsFromBox<BoundsOp, BoundsType>(
1213 builder, operandLocation, compExv, info);
1214 }
1215 } else {
1216 if (detail::getRef<evaluate::ArrayRef>(designator)) {
1217 fir::ExtendedValue compExv =
1218 converter.genExprAddr(operandLocation, designator, stmtCtx);
1219 info.addr = fir::getBase(compExv);
1220 info.rawInput = info.addr;
1221 asFortran << designator.AsFortran();
1222 } else if (auto symRef = detail::getRef<semantics::SymbolRef>(designator)) {
1223 // Scalar or full array.
1224 fir::ExtendedValue dataExv = converter.getSymbolExtendedValue(*symRef);
1225 info =
1226 getDataOperandBaseAddr(converter, builder, *symRef, operandLocation);
1227 if (mlir::isa<fir::BaseBoxType>(
1228 fir::unwrapRefType(info.addr.getType()))) {
1229 bounds = genBoundsOpsFromBox<BoundsOp, BoundsType>(
1230 builder, operandLocation, dataExv, info);
1231 }
1232 bool dataExvIsAssumedSize =
1233 Fortran::semantics::IsAssumedSizeArray(symRef->get().GetUltimate());
1234 if (mlir::isa<fir::SequenceType>(fir::unwrapRefType(info.addr.getType())))
1235 bounds = genBaseBoundsOps<BoundsOp, BoundsType>(
1236 builder, operandLocation, dataExv, dataExvIsAssumedSize);
1237 asFortran << symRef->get().name().ToString();
1238 } else { // Unsupported
1239 llvm::report_fatal_error("Unsupported type of OpenACC operand");
1240 }
1241 }
1242
1243 return info;
1244 }
1245 } // namespace lower
1246 } // namespace Fortran
1247
1248 #endif // FORTRAN_LOWER_DIRECTIVES_COMMON_H