Debian Codegraph @

flang/lib/Lower/OpenACC.cpp

raw
1 //===-- OpenACC.cpp -- OpenACC directive lowering -------------------------===//
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 #include "flang/Lower/OpenACC.h"
14 #include "DirectivesCommon.h"
15 #include "flang/Common/idioms.h"
16 #include "flang/Lower/Bridge.h"
17 #include "flang/Lower/ConvertType.h"
18 #include "flang/Lower/Mangler.h"
19 #include "flang/Lower/PFTBuilder.h"
20 #include "flang/Lower/StatementContext.h"
21 #include "flang/Lower/Support/Utils.h"
22 #include "flang/Optimizer/Builder/BoxValue.h"
23 #include "flang/Optimizer/Builder/Complex.h"
24 #include "flang/Optimizer/Builder/FIRBuilder.h"
25 #include "flang/Optimizer/Builder/HLFIRTools.h"
26 #include "flang/Optimizer/Builder/IntrinsicCall.h"
27 #include "flang/Optimizer/Builder/Todo.h"
28 #include "flang/Parser/parse-tree-visitor.h"
29 #include "flang/Parser/parse-tree.h"
30 #include "flang/Semantics/expression.h"
31 #include "flang/Semantics/scope.h"
32 #include "flang/Semantics/tools.h"
33 #include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
34 #include "llvm/Frontend/OpenACC/ACC.h.inc"
35
36 // Special value for * passed in device_type or gang clauses.
37 static constexpr std::int64_t starCst = -1;
38
39 static unsigned routineCounter = 0;
40 static constexpr llvm::StringRef accRoutinePrefix = "acc_routine_";
41 static constexpr llvm::StringRef accPrivateInitName = "acc.private.init";
42 static constexpr llvm::StringRef accReductionInitName = "acc.reduction.init";
43 static constexpr llvm::StringRef accFirDescriptorPostfix = "_desc";
44
45 static mlir::Location
46 genOperandLocation(Fortran::lower::AbstractConverter &converter,
47 const Fortran::parser::AccObject &accObject) {
48 mlir::Location loc = converter.genUnknownLocation();
49 Fortran::common::visit(
50 Fortran::common::visitors{
51 [&](const Fortran::parser::Designator &designator) {
52 loc = converter.genLocation(designator.source);
53 },
54 [&](const Fortran::parser::Name &name) {
55 loc = converter.genLocation(name.source);
56 }},
57 accObject.u);
58 return loc;
59 }
60
61 static void addOperands(llvm::SmallVectorImpl<mlir::Value> &operands,
62 llvm::SmallVectorImpl<int32_t> &operandSegments,
63 llvm::ArrayRef<mlir::Value> clauseOperands) {
64 operands.append(clauseOperands.begin(), clauseOperands.end());
65 operandSegments.push_back(clauseOperands.size());
66 }
67
68 static void addOperand(llvm::SmallVectorImpl<mlir::Value> &operands,
69 llvm::SmallVectorImpl<int32_t> &operandSegments,
70 const mlir::Value &clauseOperand) {
71 if (clauseOperand) {
72 operands.push_back(clauseOperand);
73 operandSegments.push_back(1);
74 } else {
75 operandSegments.push_back(0);
76 }
77 }
78
79 template <typename Op>
80 static Op
81 createDataEntryOp(fir::FirOpBuilder &builder, mlir::Location loc,
82 mlir::Value baseAddr, std::stringstream &name,
83 mlir::SmallVector<mlir::Value> bounds, bool structured,
84 bool implicit, mlir::acc::DataClause dataClause,
85 mlir::Type retTy, llvm::ArrayRef<mlir::Value> async,
86 llvm::ArrayRef<mlir::Attribute> asyncDeviceTypes,
87 llvm::ArrayRef<mlir::Attribute> asyncOnlyDeviceTypes,
88 mlir::Value isPresent = {}) {
89 mlir::Value varPtrPtr;
90 if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(baseAddr.getType())) {
91 if (isPresent) {
92 mlir::Type ifRetTy = boxTy.getEleTy();
93 if (!fir::isa_ref_type(ifRetTy))
94 ifRetTy = fir::ReferenceType::get(ifRetTy);
95 baseAddr =
96 builder
97 .genIfOp(loc, {ifRetTy}, isPresent,
98 /*withElseRegion=*/true)
99 .genThen([&]() {
100 mlir::Value boxAddr =
101 builder.create<fir::BoxAddrOp>(loc, baseAddr);
102 builder.create<fir::ResultOp>(loc, mlir::ValueRange{boxAddr});
103 })
104 .genElse([&] {
105 mlir::Value absent =
106 builder.create<fir::AbsentOp>(loc, ifRetTy);
107 builder.create<fir::ResultOp>(loc, mlir::ValueRange{absent});
108 })
109 .getResults()[0];
110 } else {
111 baseAddr = builder.create<fir::BoxAddrOp>(loc, baseAddr);
112 }
113 retTy = baseAddr.getType();
114 }
115
116 llvm::SmallVector<mlir::Value, 8> operands;
117 llvm::SmallVector<int32_t, 8> operandSegments;
118
119 addOperand(operands, operandSegments, baseAddr);
120 addOperand(operands, operandSegments, varPtrPtr);
121 addOperands(operands, operandSegments, bounds);
122 addOperands(operands, operandSegments, async);
123
124 Op op = builder.create<Op>(loc, retTy, operands);
125 op.setNameAttr(builder.getStringAttr(name.str()));
126 op.setStructured(structured);
127 op.setImplicit(implicit);
128 op.setDataClause(dataClause);
129 op->setAttr(Op::getOperandSegmentSizeAttr(),
130 builder.getDenseI32ArrayAttr(operandSegments));
131 if (!asyncDeviceTypes.empty())
132 op.setAsyncOperandsDeviceTypeAttr(builder.getArrayAttr(asyncDeviceTypes));
133 if (!asyncOnlyDeviceTypes.empty())
134 op.setAsyncOnlyAttr(builder.getArrayAttr(asyncOnlyDeviceTypes));
135 return op;
136 }
137
138 static void addDeclareAttr(fir::FirOpBuilder &builder, mlir::Operation *op,
139 mlir::acc::DataClause clause) {
140 if (!op)
141 return;
142 op->setAttr(mlir::acc::getDeclareAttrName(),
143 mlir::acc::DeclareAttr::get(builder.getContext(),
144 mlir::acc::DataClauseAttr::get(
145 builder.getContext(), clause)));
146 }
147
148 static mlir::func::FuncOp
149 createDeclareFunc(mlir::OpBuilder &modBuilder, fir::FirOpBuilder &builder,
150 mlir::Location loc, llvm::StringRef funcName,
151 llvm::SmallVector<mlir::Type> argsTy = {},
152 llvm::SmallVector<mlir::Location> locs = {}) {
153 auto funcTy = mlir::FunctionType::get(modBuilder.getContext(), argsTy, {});
154 auto funcOp = modBuilder.create<mlir::func::FuncOp>(loc, funcName, funcTy);
155 funcOp.setVisibility(mlir::SymbolTable::Visibility::Private);
156 builder.createBlock(&funcOp.getRegion(), funcOp.getRegion().end(), argsTy,
157 locs);
158 builder.setInsertionPointToEnd(&funcOp.getRegion().back());
159 builder.create<mlir::func::ReturnOp>(loc);
160 builder.setInsertionPointToStart(&funcOp.getRegion().back());
161 return funcOp;
162 }
163
164 template <typename Op>
165 static Op
166 createSimpleOp(fir::FirOpBuilder &builder, mlir::Location loc,
167 const llvm::SmallVectorImpl<mlir::Value> &operands,
168 const llvm::SmallVectorImpl<int32_t> &operandSegments) {
169 llvm::ArrayRef<mlir::Type> argTy;
170 Op op = builder.create<Op>(loc, argTy, operands);
171 op->setAttr(Op::getOperandSegmentSizeAttr(),
172 builder.getDenseI32ArrayAttr(operandSegments));
173 return op;
174 }
175
176 template <typename EntryOp>
177 static void createDeclareAllocFuncWithArg(mlir::OpBuilder &modBuilder,
178 fir::FirOpBuilder &builder,
179 mlir::Location loc, mlir::Type descTy,
180 llvm::StringRef funcNamePrefix,
181 std::stringstream &asFortran,
182 mlir::acc::DataClause clause) {
183 auto crtInsPt = builder.saveInsertionPoint();
184 std::stringstream registerFuncName;
185 registerFuncName << funcNamePrefix.str()
186 << Fortran::lower::declarePostAllocSuffix.str();
187
188 if (!mlir::isa<fir::ReferenceType>(descTy))
189 descTy = fir::ReferenceType::get(descTy);
190 auto registerFuncOp = createDeclareFunc(
191 modBuilder, builder, loc, registerFuncName.str(), {descTy}, {loc});
192
193 llvm::SmallVector<mlir::Value> bounds;
194 std::stringstream asFortranDesc;
195 asFortranDesc << asFortran.str() << accFirDescriptorPostfix.str();
196
197 // Updating descriptor must occur before the mapping of the data so that
198 // attached data pointer is not overwritten.
199 mlir::acc::UpdateDeviceOp updateDeviceOp =
200 createDataEntryOp<mlir::acc::UpdateDeviceOp>(
201 builder, loc, registerFuncOp.getArgument(0), asFortranDesc, bounds,
202 /*structured=*/false, /*implicit=*/true,
203 mlir::acc::DataClause::acc_update_device, descTy,
204 /*async=*/{}, /*asyncDeviceTypes=*/{}, /*asyncOnlyDeviceTypes=*/{});
205 llvm::SmallVector<int32_t> operandSegments{0, 0, 0, 1};
206 llvm::SmallVector<mlir::Value> operands{updateDeviceOp.getResult()};
207 createSimpleOp<mlir::acc::UpdateOp>(builder, loc, operands, operandSegments);
208
209 mlir::Value desc =
210 builder.create<fir::LoadOp>(loc, registerFuncOp.getArgument(0));
211 fir::BoxAddrOp boxAddrOp = builder.create<fir::BoxAddrOp>(loc, desc);
212 addDeclareAttr(builder, boxAddrOp.getOperation(), clause);
213 EntryOp entryOp = createDataEntryOp<EntryOp>(
214 builder, loc, boxAddrOp.getResult(), asFortran, bounds,
215 /*structured=*/false, /*implicit=*/false, clause, boxAddrOp.getType(),
216 /*async=*/{}, /*asyncDeviceTypes=*/{}, /*asyncOnlyDeviceTypes=*/{});
217 builder.create<mlir::acc::DeclareEnterOp>(
218 loc, mlir::acc::DeclareTokenType::get(entryOp.getContext()),
219 mlir::ValueRange(entryOp.getAccPtr()));
220
221 modBuilder.setInsertionPointAfter(registerFuncOp);
222 builder.restoreInsertionPoint(crtInsPt);
223 }
224
225 template <typename ExitOp>
226 static void createDeclareDeallocFuncWithArg(
227 mlir::OpBuilder &modBuilder, fir::FirOpBuilder &builder, mlir::Location loc,
228 mlir::Type descTy, llvm::StringRef funcNamePrefix,
229 std::stringstream &asFortran, mlir::acc::DataClause clause) {
230 auto crtInsPt = builder.saveInsertionPoint();
231 // Generate the pre dealloc function.
232 std::stringstream preDeallocFuncName;
233 preDeallocFuncName << funcNamePrefix.str()
234 << Fortran::lower::declarePreDeallocSuffix.str();
235 if (!mlir::isa<fir::ReferenceType>(descTy))
236 descTy = fir::ReferenceType::get(descTy);
237 auto preDeallocOp = createDeclareFunc(
238 modBuilder, builder, loc, preDeallocFuncName.str(), {descTy}, {loc});
239 mlir::Value loadOp =
240 builder.create<fir::LoadOp>(loc, preDeallocOp.getArgument(0));
241 fir::BoxAddrOp boxAddrOp = builder.create<fir::BoxAddrOp>(loc, loadOp);
242 addDeclareAttr(builder, boxAddrOp.getOperation(), clause);
243
244 llvm::SmallVector<mlir::Value> bounds;
245 mlir::acc::GetDevicePtrOp entryOp =
246 createDataEntryOp<mlir::acc::GetDevicePtrOp>(
247 builder, loc, boxAddrOp.getResult(), asFortran, bounds,
248 /*structured=*/false, /*implicit=*/false, clause, boxAddrOp.getType(),
249 /*async=*/{}, /*asyncDeviceTypes=*/{}, /*asyncOnlyDeviceTypes=*/{});
250 builder.create<mlir::acc::DeclareExitOp>(
251 loc, mlir::Value{}, mlir::ValueRange(entryOp.getAccPtr()));
252
253 if constexpr (std::is_same_v<ExitOp, mlir::acc::CopyoutOp> ||
254 std::is_same_v<ExitOp, mlir::acc::UpdateHostOp>)
255 builder.create<ExitOp>(entryOp.getLoc(), entryOp.getAccPtr(),
256 entryOp.getVarPtr(), entryOp.getBounds(),
257 entryOp.getAsyncOperands(),
258 entryOp.getAsyncOperandsDeviceTypeAttr(),
259 entryOp.getAsyncOnlyAttr(), entryOp.getDataClause(),
260 /*structured=*/false, /*implicit=*/false,
261 builder.getStringAttr(*entryOp.getName()));
262 else
263 builder.create<ExitOp>(entryOp.getLoc(), entryOp.getAccPtr(),
264 entryOp.getBounds(), entryOp.getAsyncOperands(),
265 entryOp.getAsyncOperandsDeviceTypeAttr(),
266 entryOp.getAsyncOnlyAttr(), entryOp.getDataClause(),
267 /*structured=*/false, /*implicit=*/false,
268 builder.getStringAttr(*entryOp.getName()));
269
270 // Generate the post dealloc function.
271 modBuilder.setInsertionPointAfter(preDeallocOp);
272 std::stringstream postDeallocFuncName;
273 postDeallocFuncName << funcNamePrefix.str()
274 << Fortran::lower::declarePostDeallocSuffix.str();
275 auto postDeallocOp = createDeclareFunc(
276 modBuilder, builder, loc, postDeallocFuncName.str(), {descTy}, {loc});
277 loadOp = builder.create<fir::LoadOp>(loc, postDeallocOp.getArgument(0));
278 asFortran << accFirDescriptorPostfix.str();
279 mlir::acc::UpdateDeviceOp updateDeviceOp =
280 createDataEntryOp<mlir::acc::UpdateDeviceOp>(
281 builder, loc, loadOp, asFortran, bounds,
282 /*structured=*/false, /*implicit=*/true,
283 mlir::acc::DataClause::acc_update_device, loadOp.getType(),
284 /*async=*/{}, /*asyncDeviceTypes=*/{}, /*asyncOnlyDeviceTypes=*/{});
285 llvm::SmallVector<int32_t> operandSegments{0, 0, 0, 1};
286 llvm::SmallVector<mlir::Value> operands{updateDeviceOp.getResult()};
287 createSimpleOp<mlir::acc::UpdateOp>(builder, loc, operands, operandSegments);
288 modBuilder.setInsertionPointAfter(postDeallocOp);
289 builder.restoreInsertionPoint(crtInsPt);
290 }
291
292 Fortran::semantics::Symbol &
293 getSymbolFromAccObject(const Fortran::parser::AccObject &accObject) {
294 if (const auto *designator =
295 std::get_if<Fortran::parser::Designator>(&accObject.u)) {
296 if (const auto *name =
297 Fortran::semantics::getDesignatorNameIfDataRef(*designator))
298 return *name->symbol;
299 if (const auto *arrayElement =
300 Fortran::parser::Unwrap<Fortran::parser::ArrayElement>(
301 *designator)) {
302 const Fortran::parser::Name &name =
303 Fortran::parser::GetLastName(arrayElement->base);
304 return *name.symbol;
305 }
306 if (const auto *component =
307 Fortran::parser::Unwrap<Fortran::parser::StructureComponent>(
308 *designator)) {
309 return *component->component.symbol;
310 }
311 } else if (const auto *name =
312 std::get_if<Fortran::parser::Name>(&accObject.u)) {
313 return *name->symbol;
314 }
315 llvm::report_fatal_error("Could not find symbol");
316 }
317
318 template <typename Op>
319 static void
320 genDataOperandOperations(const Fortran::parser::AccObjectList &objectList,
321 Fortran::lower::AbstractConverter &converter,
322 Fortran::semantics::SemanticsContext &semanticsContext,
323 Fortran::lower::StatementContext &stmtCtx,
324 llvm::SmallVectorImpl<mlir::Value> &dataOperands,
325 mlir::acc::DataClause dataClause, bool structured,
326 bool implicit, llvm::ArrayRef<mlir::Value> async,
327 llvm::ArrayRef<mlir::Attribute> asyncDeviceTypes,
328 llvm::ArrayRef<mlir::Attribute> asyncOnlyDeviceTypes,
329 bool setDeclareAttr = false) {
330 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
331 Fortran::evaluate::ExpressionAnalyzer ea{semanticsContext};
332 for (const auto &accObject : objectList.v) {
333 llvm::SmallVector<mlir::Value> bounds;
334 std::stringstream asFortran;
335 mlir::Location operandLocation = genOperandLocation(converter, accObject);
336 Fortran::semantics::Symbol &symbol = getSymbolFromAccObject(accObject);
337 Fortran::semantics::MaybeExpr designator = Fortran::common::visit(
338 [&](auto &&s) { return ea.Analyze(s); }, accObject.u);
339 Fortran::lower::AddrAndBoundsInfo info =
340 Fortran::lower::gatherDataOperandAddrAndBounds<
341 mlir::acc::DataBoundsOp, mlir::acc::DataBoundsType>(
342 converter, builder, semanticsContext, stmtCtx, symbol, designator,
343 operandLocation, asFortran, bounds,
344 /*treatIndexAsSection=*/true);
345
346 // If the input value is optional and is not a descriptor, we use the
347 // rawInput directly.
348 mlir::Value baseAddr =
349 ((info.addr.getType() != fir::unwrapRefType(info.rawInput.getType())) &&
350 info.isPresent)
351 ? info.rawInput
352 : info.addr;
353 Op op = createDataEntryOp<Op>(builder, operandLocation, baseAddr, asFortran,
354 bounds, structured, implicit, dataClause,
355 baseAddr.getType(), async, asyncDeviceTypes,
356 asyncOnlyDeviceTypes, info.isPresent);
357 dataOperands.push_back(op.getAccPtr());
358 }
359 }
360
361 template <typename EntryOp, typename ExitOp>
362 static void genDeclareDataOperandOperations(
363 const Fortran::parser::AccObjectList &objectList,
364 Fortran::lower::AbstractConverter &converter,
365 Fortran::semantics::SemanticsContext &semanticsContext,
366 Fortran::lower::StatementContext &stmtCtx,
367 llvm::SmallVectorImpl<mlir::Value> &dataOperands,
368 mlir::acc::DataClause dataClause, bool structured, bool implicit) {
369 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
370 Fortran::evaluate::ExpressionAnalyzer ea{semanticsContext};
371 for (const auto &accObject : objectList.v) {
372 llvm::SmallVector<mlir::Value> bounds;
373 std::stringstream asFortran;
374 mlir::Location operandLocation = genOperandLocation(converter, accObject);
375 Fortran::semantics::Symbol &symbol = getSymbolFromAccObject(accObject);
376 Fortran::semantics::MaybeExpr designator = Fortran::common::visit(
377 [&](auto &&s) { return ea.Analyze(s); }, accObject.u);
378 Fortran::lower::AddrAndBoundsInfo info =
379 Fortran::lower::gatherDataOperandAddrAndBounds<
380 mlir::acc::DataBoundsOp, mlir::acc::DataBoundsType>(
381 converter, builder, semanticsContext, stmtCtx, symbol, designator,
382 operandLocation, asFortran, bounds);
383 EntryOp op = createDataEntryOp<EntryOp>(
384 builder, operandLocation, info.addr, asFortran, bounds, structured,
385 implicit, dataClause, info.addr.getType(),
386 /*async=*/{}, /*asyncDeviceTypes=*/{}, /*asyncOnlyDeviceTypes=*/{});
387 dataOperands.push_back(op.getAccPtr());
388 addDeclareAttr(builder, op.getVarPtr().getDefiningOp(), dataClause);
389 if (mlir::isa<fir::BaseBoxType>(fir::unwrapRefType(info.addr.getType()))) {
390 mlir::OpBuilder modBuilder(builder.getModule().getBodyRegion());
391 modBuilder.setInsertionPointAfter(builder.getFunction());
392 std::string prefix = converter.mangleName(symbol);
393 createDeclareAllocFuncWithArg<EntryOp>(
394 modBuilder, builder, operandLocation, info.addr.getType(), prefix,
395 asFortran, dataClause);
396 if constexpr (!std::is_same_v<EntryOp, ExitOp>)
397 createDeclareDeallocFuncWithArg<ExitOp>(
398 modBuilder, builder, operandLocation, info.addr.getType(), prefix,
399 asFortran, dataClause);
400 }
401 }
402 }
403
404 template <typename EntryOp, typename ExitOp, typename Clause>
405 static void genDeclareDataOperandOperationsWithModifier(
406 const Clause *x, Fortran::lower::AbstractConverter &converter,
407 Fortran::semantics::SemanticsContext &semanticsContext,
408 Fortran::lower::StatementContext &stmtCtx,
409 Fortran::parser::AccDataModifier::Modifier mod,
410 llvm::SmallVectorImpl<mlir::Value> &dataClauseOperands,
411 const mlir::acc::DataClause clause,
412 const mlir::acc::DataClause clauseWithModifier) {
413 const Fortran::parser::AccObjectListWithModifier &listWithModifier = x->v;
414 const auto &accObjectList =
415 std::get<Fortran::parser::AccObjectList>(listWithModifier.t);
416 const auto &modifier =
417 std::get<std::optional<Fortran::parser::AccDataModifier>>(
418 listWithModifier.t);
419 mlir::acc::DataClause dataClause =
420 (modifier && (*modifier).v == mod) ? clauseWithModifier : clause;
421 genDeclareDataOperandOperations<EntryOp, ExitOp>(
422 accObjectList, converter, semanticsContext, stmtCtx, dataClauseOperands,
423 dataClause,
424 /*structured=*/true, /*implicit=*/false);
425 }
426
427 template <typename EntryOp, typename ExitOp>
428 static void genDataExitOperations(fir::FirOpBuilder &builder,
429 llvm::SmallVector<mlir::Value> operands,
430 bool structured) {
431 for (mlir::Value operand : operands) {
432 auto entryOp = mlir::dyn_cast_or_null<EntryOp>(operand.getDefiningOp());
433 assert(entryOp && "data entry op expected");
434 if constexpr (std::is_same_v<ExitOp, mlir::acc::CopyoutOp> ||
435 std::is_same_v<ExitOp, mlir::acc::UpdateHostOp>)
436 builder.create<ExitOp>(
437 entryOp.getLoc(), entryOp.getAccPtr(), entryOp.getVarPtr(),
438 entryOp.getBounds(), entryOp.getAsyncOperands(),
439 entryOp.getAsyncOperandsDeviceTypeAttr(), entryOp.getAsyncOnlyAttr(),
440 entryOp.getDataClause(), structured, entryOp.getImplicit(),
441 builder.getStringAttr(*entryOp.getName()));
442 else
443 builder.create<ExitOp>(
444 entryOp.getLoc(), entryOp.getAccPtr(), entryOp.getBounds(),
445 entryOp.getAsyncOperands(), entryOp.getAsyncOperandsDeviceTypeAttr(),
446 entryOp.getAsyncOnlyAttr(), entryOp.getDataClause(), structured,
447 entryOp.getImplicit(), builder.getStringAttr(*entryOp.getName()));
448 }
449 }
450
451 fir::ShapeOp genShapeOp(mlir::OpBuilder &builder, fir::SequenceType seqTy,
452 mlir::Location loc) {
453 llvm::SmallVector<mlir::Value> extents;
454 mlir::Type idxTy = builder.getIndexType();
455 for (auto extent : seqTy.getShape())
456 extents.push_back(builder.create<mlir::arith::ConstantOp>(
457 loc, idxTy, builder.getIntegerAttr(idxTy, extent)));
458 return builder.create<fir::ShapeOp>(loc, extents);
459 }
460
461 template <typename RecipeOp>
462 static void genPrivateLikeInitRegion(mlir::OpBuilder &builder, RecipeOp recipe,
463 mlir::Type ty, mlir::Location loc) {
464 mlir::Value retVal = recipe.getInitRegion().front().getArgument(0);
465 if (auto refTy = mlir::dyn_cast_or_null<fir::ReferenceType>(ty)) {
466 if (fir::isa_trivial(refTy.getEleTy())) {
467 auto alloca = builder.create<fir::AllocaOp>(loc, refTy.getEleTy());
468 auto declareOp = builder.create<hlfir::DeclareOp>(
469 loc, alloca, accPrivateInitName, /*shape=*/nullptr,
470 llvm::ArrayRef<mlir::Value>{}, /*dummy_scope=*/nullptr,
471 fir::FortranVariableFlagsAttr{});
472 retVal = declareOp.getBase();
473 } else if (auto seqTy = mlir::dyn_cast_or_null<fir::SequenceType>(
474 refTy.getEleTy())) {
475 if (fir::isa_trivial(seqTy.getEleTy())) {
476 mlir::Value shape;
477 llvm::SmallVector<mlir::Value> extents;
478 if (seqTy.hasDynamicExtents()) {
479 // Extents are passed as block arguments. First argument is the
480 // original value.
481 for (unsigned i = 1; i < recipe.getInitRegion().getArguments().size();
482 ++i)
483 extents.push_back(recipe.getInitRegion().getArgument(i));
484 shape = builder.create<fir::ShapeOp>(loc, extents);
485 } else {
486 shape = genShapeOp(builder, seqTy, loc);
487 }
488 auto alloca = builder.create<fir::AllocaOp>(
489 loc, seqTy, /*typeparams=*/mlir::ValueRange{}, extents);
490 auto declareOp = builder.create<hlfir::DeclareOp>(
491 loc, alloca, accPrivateInitName, shape,
492 llvm::ArrayRef<mlir::Value>{}, /*dummy_scope=*/nullptr,
493 fir::FortranVariableFlagsAttr{});
494 retVal = declareOp.getBase();
495 }
496 }
497 } else if (auto boxTy = mlir::dyn_cast_or_null<fir::BaseBoxType>(ty)) {
498 mlir::Type innerTy = fir::extractSequenceType(boxTy);
499 if (!innerTy)
500 TODO(loc, "Unsupported boxed type in OpenACC privatization");
501 fir::FirOpBuilder firBuilder{builder, recipe.getOperation()};
502 hlfir::Entity source = hlfir::Entity{retVal};
503 auto [temp, cleanup] = hlfir::createTempFromMold(loc, firBuilder, source);
504 retVal = temp;
505 }
506 builder.create<mlir::acc::YieldOp>(loc, retVal);
507 }
508
509 mlir::acc::PrivateRecipeOp
510 Fortran::lower::createOrGetPrivateRecipe(mlir::OpBuilder &builder,
511 llvm::StringRef recipeName,
512 mlir::Location loc, mlir::Type ty) {
513 mlir::ModuleOp mod =
514 builder.getBlock()->getParent()->getParentOfType<mlir::ModuleOp>();
515 if (auto recipe = mod.lookupSymbol<mlir::acc::PrivateRecipeOp>(recipeName))
516 return recipe;
517
518 auto crtPos = builder.saveInsertionPoint();
519 mlir::OpBuilder modBuilder(mod.getBodyRegion());
520 auto recipe =
521 modBuilder.create<mlir::acc::PrivateRecipeOp>(loc, recipeName, ty);
522 llvm::SmallVector<mlir::Type> argsTy{ty};
523 llvm::SmallVector<mlir::Location> argsLoc{loc};
524 if (auto refTy = mlir::dyn_cast_or_null<fir::ReferenceType>(ty)) {
525 if (auto seqTy =
526 mlir::dyn_cast_or_null<fir::SequenceType>(refTy.getEleTy())) {
527 if (seqTy.hasDynamicExtents()) {
528 mlir::Type idxTy = builder.getIndexType();
529 for (unsigned i = 0; i < seqTy.getDimension(); ++i) {
530 argsTy.push_back(idxTy);
531 argsLoc.push_back(loc);
532 }
533 }
534 }
535 }
536 builder.createBlock(&recipe.getInitRegion(), recipe.getInitRegion().end(),
537 argsTy, argsLoc);
538 builder.setInsertionPointToEnd(&recipe.getInitRegion().back());
539 genPrivateLikeInitRegion<mlir::acc::PrivateRecipeOp>(builder, recipe, ty,
540 loc);
541 builder.restoreInsertionPoint(crtPos);
542 return recipe;
543 }
544
545 /// Check if the DataBoundsOp is a constant bound (lb and ub are constants or
546 /// extent is a constant).
547 bool isConstantBound(mlir::acc::DataBoundsOp &op) {
548 if (op.getLowerbound() && fir::getIntIfConstant(op.getLowerbound()) &&
549 op.getUpperbound() && fir::getIntIfConstant(op.getUpperbound()))
550 return true;
551 if (op.getExtent() && fir::getIntIfConstant(op.getExtent()))
552 return true;
553 return false;
554 }
555
556 /// Return true iff all the bounds are expressed with constant values.
557 bool areAllBoundConstant(const llvm::SmallVector<mlir::Value> &bounds) {
558 for (auto bound : bounds) {
559 auto dataBound =
560 mlir::dyn_cast<mlir::acc::DataBoundsOp>(bound.getDefiningOp());
561 assert(dataBound && "Must be DataBoundOp operation");
562 if (!isConstantBound(dataBound))
563 return false;
564 }
565 return true;
566 }
567
568 static llvm::SmallVector<mlir::Value>
569 genConstantBounds(fir::FirOpBuilder &builder, mlir::Location loc,
570 mlir::acc::DataBoundsOp &dataBound) {
571 mlir::Type idxTy = builder.getIndexType();
572 mlir::Value lb, ub, step;
573 if (dataBound.getLowerbound() &&
574 fir::getIntIfConstant(dataBound.getLowerbound()) &&
575 dataBound.getUpperbound() &&
576 fir::getIntIfConstant(dataBound.getUpperbound())) {
577 lb = builder.createIntegerConstant(
578 loc, idxTy, *fir::getIntIfConstant(dataBound.getLowerbound()));
579 ub = builder.createIntegerConstant(
580 loc, idxTy, *fir::getIntIfConstant(dataBound.getUpperbound()));
581 step = builder.createIntegerConstant(loc, idxTy, 1);
582 } else if (dataBound.getExtent()) {
583 lb = builder.createIntegerConstant(loc, idxTy, 0);
584 ub = builder.createIntegerConstant(
585 loc, idxTy, *fir::getIntIfConstant(dataBound.getExtent()) - 1);
586 step = builder.createIntegerConstant(loc, idxTy, 1);
587 } else {
588 llvm::report_fatal_error("Expect constant lb/ub or extent");
589 }
590 return {lb, ub, step};
591 }
592
593 static fir::ShapeOp genShapeFromBoundsOrArgs(
594 mlir::Location loc, fir::FirOpBuilder &builder, fir::SequenceType seqTy,
595 const llvm::SmallVector<mlir::Value> &bounds, mlir::ValueRange arguments) {
596 llvm::SmallVector<mlir::Value> args;
597 if (areAllBoundConstant(bounds)) {
598 for (auto bound : llvm::reverse(bounds)) {
599 auto dataBound =
600 mlir::cast<mlir::acc::DataBoundsOp>(bound.getDefiningOp());
601 args.append(genConstantBounds(builder, loc, dataBound));
602 }
603 } else {
604 assert(((arguments.size() - 2) / 3 == seqTy.getDimension()) &&
605 "Expect 3 block arguments per dimension");
606 for (auto arg : arguments.drop_front(2))
607 args.push_back(arg);
608 }
609
610 assert(args.size() % 3 == 0 && "Triplets must be a multiple of 3");
611 llvm::SmallVector<mlir::Value> extents;
612 mlir::Type idxTy = builder.getIndexType();
613 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1);
614 mlir::Value zero = builder.createIntegerConstant(loc, idxTy, 0);
615 for (unsigned i = 0; i < args.size(); i += 3) {
616 mlir::Value s1 =
617 builder.create<mlir::arith::SubIOp>(loc, args[i + 1], args[0]);
618 mlir::Value s2 = builder.create<mlir::arith::AddIOp>(loc, s1, one);
619 mlir::Value s3 = builder.create<mlir::arith::DivSIOp>(loc, s2, args[i + 2]);
620 mlir::Value cmp = builder.create<mlir::arith::CmpIOp>(
621 loc, mlir::arith::CmpIPredicate::sgt, s3, zero);
622 mlir::Value ext = builder.create<mlir::arith::SelectOp>(loc, cmp, s3, zero);
623 extents.push_back(ext);
624 }
625 return builder.create<fir::ShapeOp>(loc, extents);
626 }
627
628 static hlfir::DesignateOp::Subscripts
629 getSubscriptsFromArgs(mlir::ValueRange args) {
630 hlfir::DesignateOp::Subscripts triplets;
631 for (unsigned i = 2; i < args.size(); i += 3)
632 triplets.emplace_back(
633 hlfir::DesignateOp::Triplet{args[i], args[i + 1], args[i + 2]});
634 return triplets;
635 }
636
637 static hlfir::Entity genDesignateWithTriplets(
638 fir::FirOpBuilder &builder, mlir::Location loc, hlfir::Entity &entity,
639 hlfir::DesignateOp::Subscripts &triplets, mlir::Value shape) {
640 llvm::SmallVector<mlir::Value> lenParams;
641 hlfir::genLengthParameters(loc, builder, entity, lenParams);
642 auto designate = builder.create<hlfir::DesignateOp>(
643 loc, entity.getBase().getType(), entity, /*component=*/"",
644 /*componentShape=*/mlir::Value{}, triplets,
645 /*substring=*/mlir::ValueRange{}, /*complexPartAttr=*/std::nullopt, shape,
646 lenParams);
647 return hlfir::Entity{designate.getResult()};
648 }
649
650 mlir::acc::FirstprivateRecipeOp Fortran::lower::createOrGetFirstprivateRecipe(
651 mlir::OpBuilder &builder, llvm::StringRef recipeName, mlir::Location loc,
652 mlir::Type ty, llvm::SmallVector<mlir::Value> &bounds) {
653 mlir::ModuleOp mod =
654 builder.getBlock()->getParent()->getParentOfType<mlir::ModuleOp>();
655 if (auto recipe =
656 mod.lookupSymbol<mlir::acc::FirstprivateRecipeOp>(recipeName))
657 return recipe;
658
659 auto crtPos = builder.saveInsertionPoint();
660 mlir::OpBuilder modBuilder(mod.getBodyRegion());
661 auto recipe =
662 modBuilder.create<mlir::acc::FirstprivateRecipeOp>(loc, recipeName, ty);
663 llvm::SmallVector<mlir::Type> initArgsTy{ty};
664 llvm::SmallVector<mlir::Location> initArgsLoc{loc};
665 auto refTy = fir::unwrapRefType(ty);
666 if (auto seqTy = mlir::dyn_cast_or_null<fir::SequenceType>(refTy)) {
667 if (seqTy.hasDynamicExtents()) {
668 mlir::Type idxTy = builder.getIndexType();
669 for (unsigned i = 0; i < seqTy.getDimension(); ++i) {
670 initArgsTy.push_back(idxTy);
671 initArgsLoc.push_back(loc);
672 }
673 }
674 }
675 builder.createBlock(&recipe.getInitRegion(), recipe.getInitRegion().end(),
676 initArgsTy, initArgsLoc);
677 builder.setInsertionPointToEnd(&recipe.getInitRegion().back());
678 genPrivateLikeInitRegion<mlir::acc::FirstprivateRecipeOp>(builder, recipe, ty,
679 loc);
680
681 bool allConstantBound = areAllBoundConstant(bounds);
682 llvm::SmallVector<mlir::Type> argsTy{ty, ty};
683 llvm::SmallVector<mlir::Location> argsLoc{loc, loc};
684 if (!allConstantBound) {
685 for (mlir::Value bound : llvm::reverse(bounds)) {
686 auto dataBound =
687 mlir::dyn_cast<mlir::acc::DataBoundsOp>(bound.getDefiningOp());
688 argsTy.push_back(dataBound.getLowerbound().getType());
689 argsLoc.push_back(dataBound.getLowerbound().getLoc());
690 argsTy.push_back(dataBound.getUpperbound().getType());
691 argsLoc.push_back(dataBound.getUpperbound().getLoc());
692 argsTy.push_back(dataBound.getStartIdx().getType());
693 argsLoc.push_back(dataBound.getStartIdx().getLoc());
694 }
695 }
696 builder.createBlock(&recipe.getCopyRegion(), recipe.getCopyRegion().end(),
697 argsTy, argsLoc);
698
699 builder.setInsertionPointToEnd(&recipe.getCopyRegion().back());
700 ty = fir::unwrapRefType(ty);
701 if (fir::isa_trivial(ty)) {
702 mlir::Value initValue = builder.create<fir::LoadOp>(
703 loc, recipe.getCopyRegion().front().getArgument(0));
704 builder.create<fir::StoreOp>(loc, initValue,
705 recipe.getCopyRegion().front().getArgument(1));
706 } else if (auto seqTy = mlir::dyn_cast_or_null<fir::SequenceType>(ty)) {
707 fir::FirOpBuilder firBuilder{builder, recipe.getOperation()};
708 auto shape = genShapeFromBoundsOrArgs(
709 loc, firBuilder, seqTy, bounds, recipe.getCopyRegion().getArguments());
710
711 auto leftDeclOp = builder.create<hlfir::DeclareOp>(
712 loc, recipe.getCopyRegion().getArgument(0), llvm::StringRef{}, shape,
713 llvm::ArrayRef<mlir::Value>{}, /*dummy_scope=*/nullptr,
714 fir::FortranVariableFlagsAttr{});
715 auto rightDeclOp = builder.create<hlfir::DeclareOp>(
716 loc, recipe.getCopyRegion().getArgument(1), llvm::StringRef{}, shape,
717 llvm::ArrayRef<mlir::Value>{}, /*dummy_scope=*/nullptr,
718 fir::FortranVariableFlagsAttr{});
719
720 hlfir::DesignateOp::Subscripts triplets =
721 getSubscriptsFromArgs(recipe.getCopyRegion().getArguments());
722 auto leftEntity = hlfir::Entity{leftDeclOp.getBase()};
723 auto left =
724 genDesignateWithTriplets(firBuilder, loc, leftEntity, triplets, shape);
725 auto rightEntity = hlfir::Entity{rightDeclOp.getBase()};
726 auto right =
727 genDesignateWithTriplets(firBuilder, loc, rightEntity, triplets, shape);
728
729 firBuilder.create<hlfir::AssignOp>(loc, left, right);
730
731 } else if (auto boxTy = mlir::dyn_cast_or_null<fir::BaseBoxType>(ty)) {
732 fir::FirOpBuilder firBuilder{builder, recipe.getOperation()};
733 llvm::SmallVector<mlir::Value> tripletArgs;
734 mlir::Type innerTy = fir::extractSequenceType(boxTy);
735 fir::SequenceType seqTy =
736 mlir::dyn_cast_or_null<fir::SequenceType>(innerTy);
737 if (!seqTy)
738 TODO(loc, "Unsupported boxed type in OpenACC firstprivate");
739
740 auto shape = genShapeFromBoundsOrArgs(
741 loc, firBuilder, seqTy, bounds, recipe.getCopyRegion().getArguments());
742 hlfir::DesignateOp::Subscripts triplets =
743 getSubscriptsFromArgs(recipe.getCopyRegion().getArguments());
744 auto leftEntity = hlfir::Entity{recipe.getCopyRegion().getArgument(0)};
745 auto left =
746 genDesignateWithTriplets(firBuilder, loc, leftEntity, triplets, shape);
747 auto rightEntity = hlfir::Entity{recipe.getCopyRegion().getArgument(1)};
748 auto right =
749 genDesignateWithTriplets(firBuilder, loc, rightEntity, triplets, shape);
750 firBuilder.create<hlfir::AssignOp>(loc, left, right);
751 }
752
753 builder.create<mlir::acc::TerminatorOp>(loc);
754 builder.restoreInsertionPoint(crtPos);
755 return recipe;
756 }
757
758 /// Get a string representation of the bounds.
759 std::string getBoundsString(llvm::SmallVector<mlir::Value> &bounds) {
760 std::stringstream boundStr;
761 if (!bounds.empty())
762 boundStr << "_section_";
763 llvm::interleave(
764 bounds,
765 [&](mlir::Value bound) {
766 auto boundsOp =
767 mlir::cast<mlir::acc::DataBoundsOp>(bound.getDefiningOp());
768 if (boundsOp.getLowerbound() &&
769 fir::getIntIfConstant(boundsOp.getLowerbound()) &&
770 boundsOp.getUpperbound() &&
771 fir::getIntIfConstant(boundsOp.getUpperbound())) {
772 boundStr << "lb" << *fir::getIntIfConstant(boundsOp.getLowerbound())
773 << ".ub" << *fir::getIntIfConstant(boundsOp.getUpperbound());
774 } else if (boundsOp.getExtent() &&
775 fir::getIntIfConstant(boundsOp.getExtent())) {
776 boundStr << "ext" << *fir::getIntIfConstant(boundsOp.getExtent());
777 } else {
778 boundStr << "?";
779 }
780 },
781 [&] { boundStr << "x"; });
782 return boundStr.str();
783 }
784
785 /// Rebuild the array type from the acc.bounds operation with constant
786 /// lowerbound/upperbound or extent.
787 mlir::Type getTypeFromBounds(llvm::SmallVector<mlir::Value> &bounds,
788 mlir::Type ty) {
789 auto seqTy =
790 mlir::dyn_cast_or_null<fir::SequenceType>(fir::unwrapRefType(ty));
791 if (!bounds.empty() && seqTy) {
792 llvm::SmallVector<int64_t> shape;
793 for (auto b : bounds) {
794 auto boundsOp =
795 mlir::dyn_cast<mlir::acc::DataBoundsOp>(b.getDefiningOp());
796 if (boundsOp.getLowerbound() &&
797 fir::getIntIfConstant(boundsOp.getLowerbound()) &&
798 boundsOp.getUpperbound() &&
799 fir::getIntIfConstant(boundsOp.getUpperbound())) {
800 int64_t ext = *fir::getIntIfConstant(boundsOp.getUpperbound()) -
801 *fir::getIntIfConstant(boundsOp.getLowerbound()) + 1;
802 shape.push_back(ext);
803 } else if (boundsOp.getExtent() &&
804 fir::getIntIfConstant(boundsOp.getExtent())) {
805 shape.push_back(*fir::getIntIfConstant(boundsOp.getExtent()));
806 } else {
807 return ty; // TODO: handle dynamic shaped array slice.
808 }
809 }
810 if (shape.empty() || shape.size() != bounds.size())
811 return ty;
812 auto newSeqTy = fir::SequenceType::get(shape, seqTy.getEleTy());
813 if (mlir::isa<fir::ReferenceType, fir::PointerType>(ty))
814 return fir::ReferenceType::get(newSeqTy);
815 return newSeqTy;
816 }
817 return ty;
818 }
819
820 template <typename RecipeOp>
821 static void
822 genPrivatizations(const Fortran::parser::AccObjectList &objectList,
823 Fortran::lower::AbstractConverter &converter,
824 Fortran::semantics::SemanticsContext &semanticsContext,
825 Fortran::lower::StatementContext &stmtCtx,
826 llvm::SmallVectorImpl<mlir::Value> &dataOperands,
827 llvm::SmallVector<mlir::Attribute> &privatizations,
828 llvm::ArrayRef<mlir::Value> async,
829 llvm::ArrayRef<mlir::Attribute> asyncDeviceTypes,
830 llvm::ArrayRef<mlir::Attribute> asyncOnlyDeviceTypes) {
831 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
832 Fortran::evaluate::ExpressionAnalyzer ea{semanticsContext};
833 for (const auto &accObject : objectList.v) {
834 llvm::SmallVector<mlir::Value> bounds;
835 std::stringstream asFortran;
836 mlir::Location operandLocation = genOperandLocation(converter, accObject);
837 Fortran::semantics::Symbol &symbol = getSymbolFromAccObject(accObject);
838 Fortran::semantics::MaybeExpr designator = Fortran::common::visit(
839 [&](auto &&s) { return ea.Analyze(s); }, accObject.u);
840 Fortran::lower::AddrAndBoundsInfo info =
841 Fortran::lower::gatherDataOperandAddrAndBounds<
842 mlir::acc::DataBoundsOp, mlir::acc::DataBoundsType>(
843 converter, builder, semanticsContext, stmtCtx, symbol, designator,
844 operandLocation, asFortran, bounds);
845 RecipeOp recipe;
846 mlir::Type retTy = getTypeFromBounds(bounds, info.addr.getType());
847 if constexpr (std::is_same_v<RecipeOp, mlir::acc::PrivateRecipeOp>) {
848 std::string recipeName =
849 fir::getTypeAsString(retTy, converter.getKindMap(),
850 Fortran::lower::privatizationRecipePrefix);
851 recipe = Fortran::lower::createOrGetPrivateRecipe(builder, recipeName,
852 operandLocation, retTy);
853 auto op = createDataEntryOp<mlir::acc::PrivateOp>(
854 builder, operandLocation, info.addr, asFortran, bounds, true,
855 /*implicit=*/false, mlir::acc::DataClause::acc_private, retTy, async,
856 asyncDeviceTypes, asyncOnlyDeviceTypes);
857 dataOperands.push_back(op.getAccPtr());
858 } else {
859 std::string suffix =
860 areAllBoundConstant(bounds) ? getBoundsString(bounds) : "";
861 std::string recipeName = fir::getTypeAsString(
862 retTy, converter.getKindMap(), "firstprivatization" + suffix);
863 recipe = Fortran::lower::createOrGetFirstprivateRecipe(
864 builder, recipeName, operandLocation, retTy, bounds);
865 auto op = createDataEntryOp<mlir::acc::FirstprivateOp>(
866 builder, operandLocation, info.addr, asFortran, bounds, true,
867 /*implicit=*/false, mlir::acc::DataClause::acc_firstprivate, retTy,
868 async, asyncDeviceTypes, asyncOnlyDeviceTypes);
869 dataOperands.push_back(op.getAccPtr());
870 }
871 privatizations.push_back(mlir::SymbolRefAttr::get(
872 builder.getContext(), recipe.getSymName().str()));
873 }
874 }
875
876 /// Return the corresponding enum value for the mlir::acc::ReductionOperator
877 /// from the parser representation.
878 static mlir::acc::ReductionOperator
879 getReductionOperator(const Fortran::parser::ReductionOperator &op) {
880 switch (op.v) {
881 case Fortran::parser::ReductionOperator::Operator::Plus:
882 return mlir::acc::ReductionOperator::AccAdd;
883 case Fortran::parser::ReductionOperator::Operator::Multiply:
884 return mlir::acc::ReductionOperator::AccMul;
885 case Fortran::parser::ReductionOperator::Operator::Max:
886 return mlir::acc::ReductionOperator::AccMax;
887 case Fortran::parser::ReductionOperator::Operator::Min:
888 return mlir::acc::ReductionOperator::AccMin;
889 case Fortran::parser::ReductionOperator::Operator::Iand:
890 return mlir::acc::ReductionOperator::AccIand;
891 case Fortran::parser::ReductionOperator::Operator::Ior:
892 return mlir::acc::ReductionOperator::AccIor;
893 case Fortran::parser::ReductionOperator::Operator::Ieor:
894 return mlir::acc::ReductionOperator::AccXor;
895 case Fortran::parser::ReductionOperator::Operator::And:
896 return mlir::acc::ReductionOperator::AccLand;
897 case Fortran::parser::ReductionOperator::Operator::Or:
898 return mlir::acc::ReductionOperator::AccLor;
899 case Fortran::parser::ReductionOperator::Operator::Eqv:
900 return mlir::acc::ReductionOperator::AccEqv;
901 case Fortran::parser::ReductionOperator::Operator::Neqv:
902 return mlir::acc::ReductionOperator::AccNeqv;
903 }
904 llvm_unreachable("unexpected reduction operator");
905 }
906
907 /// Get the initial value for reduction operator.
908 template <typename R>
909 static R getReductionInitValue(mlir::acc::ReductionOperator op, mlir::Type ty) {
910 if (op == mlir::acc::ReductionOperator::AccMin) {
911 // min init value -> largest
912 if constexpr (std::is_same_v<R, llvm::APInt>) {
913 assert(ty.isIntOrIndex() && "expect integer or index type");
914 return llvm::APInt::getSignedMaxValue(ty.getIntOrFloatBitWidth());
915 }
916 if constexpr (std::is_same_v<R, llvm::APFloat>) {
917 auto floatTy = mlir::dyn_cast_or_null<mlir::FloatType>(ty);
918 assert(floatTy && "expect float type");
919 return llvm::APFloat::getLargest(floatTy.getFloatSemantics(),
920 /*negative=*/false);
921 }
922 } else if (op == mlir::acc::ReductionOperator::AccMax) {
923 // max init value -> smallest
924 if constexpr (std::is_same_v<R, llvm::APInt>) {
925 assert(ty.isIntOrIndex() && "expect integer or index type");
926 return llvm::APInt::getSignedMinValue(ty.getIntOrFloatBitWidth());
927 }
928 if constexpr (std::is_same_v<R, llvm::APFloat>) {
929 auto floatTy = mlir::dyn_cast_or_null<mlir::FloatType>(ty);
930 assert(floatTy && "expect float type");
931 return llvm::APFloat::getSmallest(floatTy.getFloatSemantics(),
932 /*negative=*/true);
933 }
934 } else if (op == mlir::acc::ReductionOperator::AccIand) {
935 if constexpr (std::is_same_v<R, llvm::APInt>) {
936 assert(ty.isIntOrIndex() && "expect integer type");
937 unsigned bits = ty.getIntOrFloatBitWidth();
938 return llvm::APInt::getAllOnes(bits);
939 }
940 } else {
941 // +, ior, ieor init value -> 0
942 // * init value -> 1
943 int64_t value = (op == mlir::acc::ReductionOperator::AccMul) ? 1 : 0;
944 if constexpr (std::is_same_v<R, llvm::APInt>) {
945 assert(ty.isIntOrIndex() && "expect integer or index type");
946 return llvm::APInt(ty.getIntOrFloatBitWidth(), value, true);
947 }
948
949 if constexpr (std::is_same_v<R, llvm::APFloat>) {
950 assert(mlir::isa<mlir::FloatType>(ty) && "expect float type");
951 auto floatTy = mlir::dyn_cast<mlir::FloatType>(ty);
952 return llvm::APFloat(floatTy.getFloatSemantics(), value);
953 }
954
955 if constexpr (std::is_same_v<R, int64_t>)
956 return value;
957 }
958 llvm_unreachable("OpenACC reduction unsupported type");
959 }
960
961 /// Return a constant with the initial value for the reduction operator and
962 /// type combination.
963 static mlir::Value getReductionInitValue(fir::FirOpBuilder &builder,
964 mlir::Location loc, mlir::Type ty,
965 mlir::acc::ReductionOperator op) {
966 if (op == mlir::acc::ReductionOperator::AccLand ||
967 op == mlir::acc::ReductionOperator::AccLor ||
968 op == mlir::acc::ReductionOperator::AccEqv ||
969 op == mlir::acc::ReductionOperator::AccNeqv) {
970 assert(mlir::isa<fir::LogicalType>(ty) && "expect fir.logical type");
971 bool value = true; // .true. for .and. and .eqv.
972 if (op == mlir::acc::ReductionOperator::AccLor ||
973 op == mlir::acc::ReductionOperator::AccNeqv)
974 value = false; // .false. for .or. and .neqv.
975 return builder.createBool(loc, value);
976 }
977 if (ty.isIntOrIndex())
978 return builder.create<mlir::arith::ConstantOp>(
979 loc, ty,
980 builder.getIntegerAttr(ty, getReductionInitValue<llvm::APInt>(op, ty)));
981 if (op == mlir::acc::ReductionOperator::AccMin ||
982 op == mlir::acc::ReductionOperator::AccMax) {
983 if (mlir::isa<fir::ComplexType>(ty))
984 llvm::report_fatal_error(
985 "min/max reduction not supported for complex type");
986 if (auto floatTy = mlir::dyn_cast_or_null<mlir::FloatType>(ty))
987 return builder.create<mlir::arith::ConstantOp>(
988 loc, ty,
989 builder.getFloatAttr(ty,
990 getReductionInitValue<llvm::APFloat>(op, ty)));
991 } else if (auto floatTy = mlir::dyn_cast_or_null<mlir::FloatType>(ty)) {
992 return builder.create<mlir::arith::ConstantOp>(
993 loc, ty,
994 builder.getFloatAttr(ty, getReductionInitValue<int64_t>(op, ty)));
995 } else if (auto cmplxTy = mlir::dyn_cast_or_null<fir::ComplexType>(ty)) {
996 mlir::Type floatTy =
997 Fortran::lower::convertReal(builder.getContext(), cmplxTy.getFKind());
998 mlir::Value realInit = builder.createRealConstant(
999 loc, floatTy, getReductionInitValue<int64_t>(op, cmplxTy));
1000 mlir::Value imagInit = builder.createRealConstant(loc, floatTy, 0.0);
1001 return fir::factory::Complex{builder, loc}.createComplex(
1002 cmplxTy.getFKind(), realInit, imagInit);
1003 }
1004
1005 if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(ty))
1006 return getReductionInitValue(builder, loc, seqTy.getEleTy(), op);
1007
1008 if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(ty))
1009 return getReductionInitValue(builder, loc, boxTy.getEleTy(), op);
1010
1011 if (auto heapTy = mlir::dyn_cast<fir::HeapType>(ty))
1012 return getReductionInitValue(builder, loc, heapTy.getEleTy(), op);
1013
1014 if (auto ptrTy = mlir::dyn_cast<fir::PointerType>(ty))
1015 return getReductionInitValue(builder, loc, ptrTy.getEleTy(), op);
1016
1017 llvm::report_fatal_error("Unsupported OpenACC reduction type");
1018 }
1019
1020 static mlir::Value genReductionInitRegion(fir::FirOpBuilder &builder,
1021 mlir::Location loc, mlir::Type ty,
1022 mlir::acc::ReductionOperator op) {
1023 ty = fir::unwrapRefType(ty);
1024 mlir::Value initValue = getReductionInitValue(builder, loc, ty, op);
1025 if (fir::isa_trivial(ty)) {
1026 mlir::Value alloca = builder.create<fir::AllocaOp>(loc, ty);
1027 auto declareOp = builder.create<hlfir::DeclareOp>(
1028 loc, alloca, accReductionInitName, /*shape=*/nullptr,
1029 llvm::ArrayRef<mlir::Value>{}, /*dummy_scope=*/nullptr,
1030 fir::FortranVariableFlagsAttr{});
1031 builder.create<fir::StoreOp>(loc, builder.createConvert(loc, ty, initValue),
1032 declareOp.getBase());
1033 return declareOp.getBase();
1034 } else if (auto seqTy = mlir::dyn_cast_or_null<fir::SequenceType>(ty)) {
1035 if (fir::isa_trivial(seqTy.getEleTy())) {
1036 mlir::Value shape;
1037 auto extents = builder.getBlock()->getArguments().drop_front(1);
1038 if (seqTy.hasDynamicExtents())
1039 shape = builder.create<fir::ShapeOp>(loc, extents);
1040 else
1041 shape = genShapeOp(builder, seqTy, loc);
1042 mlir::Value alloca = builder.create<fir::AllocaOp>(
1043 loc, seqTy, /*typeparams=*/mlir::ValueRange{}, extents);
1044 auto declareOp = builder.create<hlfir::DeclareOp>(
1045 loc, alloca, accReductionInitName, shape,
1046 llvm::ArrayRef<mlir::Value>{}, /*dummy_scope=*/nullptr,
1047 fir::FortranVariableFlagsAttr{});
1048 mlir::Type idxTy = builder.getIndexType();
1049 mlir::Type refTy = fir::ReferenceType::get(seqTy.getEleTy());
1050 llvm::SmallVector<fir::DoLoopOp> loops;
1051 llvm::SmallVector<mlir::Value> ivs;
1052
1053 if (seqTy.hasDynamicExtents()) {
1054 builder.create<hlfir::AssignOp>(loc, initValue, declareOp.getBase());
1055 return declareOp.getBase();
1056 }
1057 for (auto ext : llvm::reverse(seqTy.getShape())) {
1058 auto lb = builder.createIntegerConstant(loc, idxTy, 0);
1059 auto ub = builder.createIntegerConstant(loc, idxTy, ext - 1);
1060 auto step = builder.createIntegerConstant(loc, idxTy, 1);
1061 auto loop = builder.create<fir::DoLoopOp>(loc, lb, ub, step,
1062 /*unordered=*/false);
1063 builder.setInsertionPointToStart(loop.getBody());
1064 loops.push_back(loop);
1065 ivs.push_back(loop.getInductionVar());
1066 }
1067 auto coord = builder.create<fir::CoordinateOp>(loc, refTy,
1068 declareOp.getBase(), ivs);
1069 builder.create<fir::StoreOp>(loc, initValue, coord);
1070 builder.setInsertionPointAfter(loops[0]);
1071 return declareOp.getBase();
1072 }
1073 } else if (auto boxTy = mlir::dyn_cast_or_null<fir::BaseBoxType>(ty)) {
1074 mlir::Type innerTy = fir::extractSequenceType(boxTy);
1075 if (!mlir::isa<fir::SequenceType>(innerTy))
1076 TODO(loc, "Unsupported boxed type for reduction");
1077 // Create the private copy from the initial fir.box.
1078 hlfir::Entity source = hlfir::Entity{builder.getBlock()->getArgument(0)};
1079 auto [temp, cleanup] = hlfir::createTempFromMold(loc, builder, source);
1080 builder.create<hlfir::AssignOp>(loc, initValue, temp);
1081 return temp;
1082 }
1083 llvm::report_fatal_error("Unsupported OpenACC reduction type");
1084 }
1085
1086 template <typename Op>
1087 static mlir::Value genLogicalCombiner(fir::FirOpBuilder &builder,
1088 mlir::Location loc, mlir::Value value1,
1089 mlir::Value value2) {
1090 mlir::Type i1 = builder.getI1Type();
1091 mlir::Value v1 = builder.create<fir::ConvertOp>(loc, i1, value1);
1092 mlir::Value v2 = builder.create<fir::ConvertOp>(loc, i1, value2);
1093 mlir::Value combined = builder.create<Op>(loc, v1, v2);
1094 return builder.create<fir::ConvertOp>(loc, value1.getType(), combined);
1095 }
1096
1097 static mlir::Value genComparisonCombiner(fir::FirOpBuilder &builder,
1098 mlir::Location loc,
1099 mlir::arith::CmpIPredicate pred,
1100 mlir::Value value1,
1101 mlir::Value value2) {
1102 mlir::Type i1 = builder.getI1Type();
1103 mlir::Value v1 = builder.create<fir::ConvertOp>(loc, i1, value1);
1104 mlir::Value v2 = builder.create<fir::ConvertOp>(loc, i1, value2);
1105 mlir::Value add = builder.create<mlir::arith::CmpIOp>(loc, pred, v1, v2);
1106 return builder.create<fir::ConvertOp>(loc, value1.getType(), add);
1107 }
1108
1109 static mlir::Value genScalarCombiner(fir::FirOpBuilder &builder,
1110 mlir::Location loc,
1111 mlir::acc::ReductionOperator op,
1112 mlir::Type ty, mlir::Value value1,
1113 mlir::Value value2) {
1114 value1 = builder.loadIfRef(loc, value1);
1115 value2 = builder.loadIfRef(loc, value2);
1116 if (op == mlir::acc::ReductionOperator::AccAdd) {
1117 if (ty.isIntOrIndex())
1118 return builder.create<mlir::arith::AddIOp>(loc, value1, value2);
1119 if (mlir::isa<mlir::FloatType>(ty))
1120 return builder.create<mlir::arith::AddFOp>(loc, value1, value2);
1121 if (auto cmplxTy = mlir::dyn_cast_or_null<fir::ComplexType>(ty))
1122 return builder.create<fir::AddcOp>(loc, value1, value2);
1123 TODO(loc, "reduction add type");
1124 }
1125
1126 if (op == mlir::acc::ReductionOperator::AccMul) {
1127 if (ty.isIntOrIndex())
1128 return builder.create<mlir::arith::MulIOp>(loc, value1, value2);
1129 if (mlir::isa<mlir::FloatType>(ty))
1130 return builder.create<mlir::arith::MulFOp>(loc, value1, value2);
1131 if (mlir::isa<fir::ComplexType>(ty))
1132 return builder.create<fir::MulcOp>(loc, value1, value2);
1133 TODO(loc, "reduction mul type");
1134 }
1135
1136 if (op == mlir::acc::ReductionOperator::AccMin)
1137 return fir::genMin(builder, loc, {value1, value2});
1138
1139 if (op == mlir::acc::ReductionOperator::AccMax)
1140 return fir::genMax(builder, loc, {value1, value2});
1141
1142 if (op == mlir::acc::ReductionOperator::AccIand)
1143 return builder.create<mlir::arith::AndIOp>(loc, value1, value2);
1144
1145 if (op == mlir::acc::ReductionOperator::AccIor)
1146 return builder.create<mlir::arith::OrIOp>(loc, value1, value2);
1147
1148 if (op == mlir::acc::ReductionOperator::AccXor)
1149 return builder.create<mlir::arith::XOrIOp>(loc, value1, value2);
1150
1151 if (op == mlir::acc::ReductionOperator::AccLand)
1152 return genLogicalCombiner<mlir::arith::AndIOp>(builder, loc, value1,
1153 value2);
1154
1155 if (op == mlir::acc::ReductionOperator::AccLor)
1156 return genLogicalCombiner<mlir::arith::OrIOp>(builder, loc, value1, value2);
1157
1158 if (op == mlir::acc::ReductionOperator::AccEqv)
1159 return genComparisonCombiner(builder, loc, mlir::arith::CmpIPredicate::eq,
1160 value1, value2);
1161
1162 if (op == mlir::acc::ReductionOperator::AccNeqv)
1163 return genComparisonCombiner(builder, loc, mlir::arith::CmpIPredicate::ne,
1164 value1, value2);
1165
1166 TODO(loc, "reduction operator");
1167 }
1168
1169 static hlfir::DesignateOp::Subscripts
1170 getTripletsFromArgs(mlir::acc::ReductionRecipeOp recipe) {
1171 hlfir::DesignateOp::Subscripts triplets;
1172 for (unsigned i = 2; i < recipe.getCombinerRegion().getArguments().size();
1173 i += 3)
1174 triplets.emplace_back(hlfir::DesignateOp::Triplet{
1175 recipe.getCombinerRegion().getArgument(i),
1176 recipe.getCombinerRegion().getArgument(i + 1),
1177 recipe.getCombinerRegion().getArgument(i + 2)});
1178 return triplets;
1179 }
1180
1181 static void genCombiner(fir::FirOpBuilder &builder, mlir::Location loc,
1182 mlir::acc::ReductionOperator op, mlir::Type ty,
1183 mlir::Value value1, mlir::Value value2,
1184 mlir::acc::ReductionRecipeOp &recipe,
1185 llvm::SmallVector<mlir::Value> &bounds,
1186 bool allConstantBound) {
1187 ty = fir::unwrapRefType(ty);
1188
1189 if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(ty)) {
1190 mlir::Type refTy = fir::ReferenceType::get(seqTy.getEleTy());
1191 llvm::SmallVector<fir::DoLoopOp> loops;
1192 llvm::SmallVector<mlir::Value> ivs;
1193 if (seqTy.hasDynamicExtents()) {
1194 auto shape =
1195 genShapeFromBoundsOrArgs(loc, builder, seqTy, bounds,
1196 recipe.getCombinerRegion().getArguments());
1197 auto v1DeclareOp = builder.create<hlfir::DeclareOp>(
1198 loc, value1, llvm::StringRef{}, shape, llvm::ArrayRef<mlir::Value>{},
1199 /*dummy_scope=*/nullptr, fir::FortranVariableFlagsAttr{});
1200 auto v2DeclareOp = builder.create<hlfir::DeclareOp>(
1201 loc, value2, llvm::StringRef{}, shape, llvm::ArrayRef<mlir::Value>{},
1202 /*dummy_scope=*/nullptr, fir::FortranVariableFlagsAttr{});
1203 hlfir::DesignateOp::Subscripts triplets = getTripletsFromArgs(recipe);
1204
1205 llvm::SmallVector<mlir::Value> lenParamsLeft;
1206 auto leftEntity = hlfir::Entity{v1DeclareOp.getBase()};
1207 hlfir::genLengthParameters(loc, builder, leftEntity, lenParamsLeft);
1208 auto leftDesignate = builder.create<hlfir::DesignateOp>(
1209 loc, v1DeclareOp.getBase().getType(), v1DeclareOp.getBase(),
1210 /*component=*/"",
1211 /*componentShape=*/mlir::Value{}, triplets,
1212 /*substring=*/mlir::ValueRange{}, /*complexPartAttr=*/std::nullopt,
1213 shape, lenParamsLeft);
1214 auto left = hlfir::Entity{leftDesignate.getResult()};
1215
1216 llvm::SmallVector<mlir::Value> lenParamsRight;
1217 auto rightEntity = hlfir::Entity{v2DeclareOp.getBase()};
1218 hlfir::genLengthParameters(loc, builder, rightEntity, lenParamsLeft);
1219 auto rightDesignate = builder.create<hlfir::DesignateOp>(
1220 loc, v2DeclareOp.getBase().getType(), v2DeclareOp.getBase(),
1221 /*component=*/"",
1222 /*componentShape=*/mlir::Value{}, triplets,
1223 /*substring=*/mlir::ValueRange{}, /*complexPartAttr=*/std::nullopt,
1224 shape, lenParamsRight);
1225 auto right = hlfir::Entity{rightDesignate.getResult()};
1226
1227 llvm::SmallVector<mlir::Value, 1> typeParams;
1228 auto genKernel = [&builder, &loc, op, seqTy, &left, &right](
1229 mlir::Location l, fir::FirOpBuilder &b,
1230 mlir::ValueRange oneBasedIndices) -> hlfir::Entity {
1231 auto leftElement = hlfir::getElementAt(l, b, left, oneBasedIndices);
1232 auto rightElement = hlfir::getElementAt(l, b, right, oneBasedIndices);
1233 auto leftVal = hlfir::loadTrivialScalar(l, b, leftElement);
1234 auto rightVal = hlfir::loadTrivialScalar(l, b, rightElement);
1235 return hlfir::Entity{genScalarCombiner(
1236 builder, loc, op, seqTy.getEleTy(), leftVal, rightVal)};
1237 };
1238 mlir::Value elemental = hlfir::genElementalOp(
1239 loc, builder, seqTy.getEleTy(), shape, typeParams, genKernel,
1240 /*isUnordered=*/true);
1241 builder.create<hlfir::AssignOp>(loc, elemental, v1DeclareOp.getBase());
1242 return;
1243 }
1244 if (allConstantBound) {
1245 // Use the constant bound directly in the combiner region so they do not
1246 // need to be passed as block argument.
1247 for (auto bound : llvm::reverse(bounds)) {
1248 auto dataBound =
1249 mlir::dyn_cast<mlir::acc::DataBoundsOp>(bound.getDefiningOp());
1250 llvm::SmallVector<mlir::Value> values =
1251 genConstantBounds(builder, loc, dataBound);
1252 auto loop =
1253 builder.create<fir::DoLoopOp>(loc, values[0], values[1], values[2],
1254 /*unordered=*/false);
1255 builder.setInsertionPointToStart(loop.getBody());
1256 loops.push_back(loop);
1257 ivs.push_back(loop.getInductionVar());
1258 }
1259 } else {
1260 // Lowerbound, upperbound and step are passed as block arguments.
1261 [[maybe_unused]] unsigned nbRangeArgs =
1262 recipe.getCombinerRegion().getArguments().size() - 2;
1263 assert((nbRangeArgs / 3 == seqTy.getDimension()) &&
1264 "Expect 3 block arguments per dimension");
1265 for (unsigned i = 2; i < recipe.getCombinerRegion().getArguments().size();
1266 i += 3) {
1267 mlir::Value lb = recipe.getCombinerRegion().getArgument(i);
1268 mlir::Value ub = recipe.getCombinerRegion().getArgument(i + 1);
1269 mlir::Value step = recipe.getCombinerRegion().getArgument(i + 2);
1270 auto loop = builder.create<fir::DoLoopOp>(loc, lb, ub, step,
1271 /*unordered=*/false);
1272 builder.setInsertionPointToStart(loop.getBody());
1273 loops.push_back(loop);
1274 ivs.push_back(loop.getInductionVar());
1275 }
1276 }
1277 auto addr1 = builder.create<fir::CoordinateOp>(loc, refTy, value1, ivs);
1278 auto addr2 = builder.create<fir::CoordinateOp>(loc, refTy, value2, ivs);
1279 auto load1 = builder.create<fir::LoadOp>(loc, addr1);
1280 auto load2 = builder.create<fir::LoadOp>(loc, addr2);
1281 mlir::Value res =
1282 genScalarCombiner(builder, loc, op, seqTy.getEleTy(), load1, load2);
1283 builder.create<fir::StoreOp>(loc, res, addr1);
1284 builder.setInsertionPointAfter(loops[0]);
1285 } else if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(ty)) {
1286 mlir::Type innerTy = fir::extractSequenceType(boxTy);
1287 fir::SequenceType seqTy =
1288 mlir::dyn_cast_or_null<fir::SequenceType>(innerTy);
1289 if (!seqTy)
1290 TODO(loc, "Unsupported boxed type in OpenACC reduction");
1291
1292 auto shape = genShapeFromBoundsOrArgs(
1293 loc, builder, seqTy, bounds, recipe.getCombinerRegion().getArguments());
1294 hlfir::DesignateOp::Subscripts triplets =
1295 getSubscriptsFromArgs(recipe.getCombinerRegion().getArguments());
1296 auto leftEntity = hlfir::Entity{value1};
1297 auto left =
1298 genDesignateWithTriplets(builder, loc, leftEntity, triplets, shape);
1299 auto rightEntity = hlfir::Entity{value2};
1300 auto right =
1301 genDesignateWithTriplets(builder, loc, rightEntity, triplets, shape);
1302
1303 llvm::SmallVector<mlir::Value, 1> typeParams;
1304 auto genKernel = [&builder, &loc, op, seqTy, &left, &right](
1305 mlir::Location l, fir::FirOpBuilder &b,
1306 mlir::ValueRange oneBasedIndices) -> hlfir::Entity {
1307 auto leftElement = hlfir::getElementAt(l, b, left, oneBasedIndices);
1308 auto rightElement = hlfir::getElementAt(l, b, right, oneBasedIndices);
1309 auto leftVal = hlfir::loadTrivialScalar(l, b, leftElement);
1310 auto rightVal = hlfir::loadTrivialScalar(l, b, rightElement);
1311 return hlfir::Entity{genScalarCombiner(builder, loc, op, seqTy.getEleTy(),
1312 leftVal, rightVal)};
1313 };
1314 mlir::Value elemental = hlfir::genElementalOp(
1315 loc, builder, seqTy.getEleTy(), shape, typeParams, genKernel,
1316 /*isUnordered=*/true);
1317 builder.create<hlfir::AssignOp>(loc, elemental, value1);
1318 } else {
1319 mlir::Value res = genScalarCombiner(builder, loc, op, ty, value1, value2);
1320 builder.create<fir::StoreOp>(loc, res, value1);
1321 }
1322 }
1323
1324 mlir::acc::ReductionRecipeOp Fortran::lower::createOrGetReductionRecipe(
1325 fir::FirOpBuilder &builder, llvm::StringRef recipeName, mlir::Location loc,
1326 mlir::Type ty, mlir::acc::ReductionOperator op,
1327 llvm::SmallVector<mlir::Value> &bounds) {
1328 mlir::ModuleOp mod =
1329 builder.getBlock()->getParent()->getParentOfType<mlir::ModuleOp>();
1330 if (auto recipe = mod.lookupSymbol<mlir::acc::ReductionRecipeOp>(recipeName))
1331 return recipe;
1332
1333 auto crtPos = builder.saveInsertionPoint();
1334 mlir::OpBuilder modBuilder(mod.getBodyRegion());
1335 auto recipe =
1336 modBuilder.create<mlir::acc::ReductionRecipeOp>(loc, recipeName, ty, op);
1337 llvm::SmallVector<mlir::Type> initArgsTy{ty};
1338 llvm::SmallVector<mlir::Location> initArgsLoc{loc};
1339 mlir::Type refTy = fir::unwrapRefType(ty);
1340 if (auto seqTy = mlir::dyn_cast_or_null<fir::SequenceType>(refTy)) {
1341 if (seqTy.hasDynamicExtents()) {
1342 mlir::Type idxTy = builder.getIndexType();
1343 for (unsigned i = 0; i < seqTy.getDimension(); ++i) {
1344 initArgsTy.push_back(idxTy);
1345 initArgsLoc.push_back(loc);
1346 }
1347 }
1348 }
1349 builder.createBlock(&recipe.getInitRegion(), recipe.getInitRegion().end(),
1350 initArgsTy, initArgsLoc);
1351 builder.setInsertionPointToEnd(&recipe.getInitRegion().back());
1352 mlir::Value initValue = genReductionInitRegion(builder, loc, ty, op);
1353 builder.create<mlir::acc::YieldOp>(loc, initValue);
1354
1355 // The two first block arguments are the two values to be combined.
1356 // The next arguments are the iteration ranges (lb, ub, step) to be used
1357 // for the combiner if needed.
1358 llvm::SmallVector<mlir::Type> argsTy{ty, ty};
1359 llvm::SmallVector<mlir::Location> argsLoc{loc, loc};
1360 bool allConstantBound = areAllBoundConstant(bounds);
1361 if (!allConstantBound) {
1362 for (mlir::Value bound : llvm::reverse(bounds)) {
1363 auto dataBound =
1364 mlir::dyn_cast<mlir::acc::DataBoundsOp>(bound.getDefiningOp());
1365 argsTy.push_back(dataBound.getLowerbound().getType());
1366 argsLoc.push_back(dataBound.getLowerbound().getLoc());
1367 argsTy.push_back(dataBound.getUpperbound().getType());
1368 argsLoc.push_back(dataBound.getUpperbound().getLoc());
1369 argsTy.push_back(dataBound.getStartIdx().getType());
1370 argsLoc.push_back(dataBound.getStartIdx().getLoc());
1371 }
1372 }
1373 builder.createBlock(&recipe.getCombinerRegion(),
1374 recipe.getCombinerRegion().end(), argsTy, argsLoc);
1375 builder.setInsertionPointToEnd(&recipe.getCombinerRegion().back());
1376 mlir::Value v1 = recipe.getCombinerRegion().front().getArgument(0);
1377 mlir::Value v2 = recipe.getCombinerRegion().front().getArgument(1);
1378 genCombiner(builder, loc, op, ty, v1, v2, recipe, bounds, allConstantBound);
1379 builder.create<mlir::acc::YieldOp>(loc, v1);
1380 builder.restoreInsertionPoint(crtPos);
1381 return recipe;
1382 }
1383
1384 static bool isSupportedReductionType(mlir::Type ty) {
1385 ty = fir::unwrapRefType(ty);
1386 if (auto boxTy = mlir::dyn_cast<fir::BaseBoxType>(ty))
1387 return isSupportedReductionType(boxTy.getEleTy());
1388 if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(ty))
1389 return isSupportedReductionType(seqTy.getEleTy());
1390 if (auto heapTy = mlir::dyn_cast<fir::HeapType>(ty))
1391 return isSupportedReductionType(heapTy.getEleTy());
1392 if (auto ptrTy = mlir::dyn_cast<fir::PointerType>(ty))
1393 return isSupportedReductionType(ptrTy.getEleTy());
1394 return fir::isa_trivial(ty);
1395 }
1396
1397 static void
1398 genReductions(const Fortran::parser::AccObjectListWithReduction &objectList,
1399 Fortran::lower::AbstractConverter &converter,
1400 Fortran::semantics::SemanticsContext &semanticsContext,
1401 Fortran::lower::StatementContext &stmtCtx,
1402 llvm::SmallVectorImpl<mlir::Value> &reductionOperands,
1403 llvm::SmallVector<mlir::Attribute> &reductionRecipes,
1404 llvm::ArrayRef<mlir::Value> async,
1405 llvm::ArrayRef<mlir::Attribute> asyncDeviceTypes,
1406 llvm::ArrayRef<mlir::Attribute> asyncOnlyDeviceTypes) {
1407 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1408 const auto &objects = std::get<Fortran::parser::AccObjectList>(objectList.t);
1409 const auto &op = std::get<Fortran::parser::ReductionOperator>(objectList.t);
1410 mlir::acc::ReductionOperator mlirOp = getReductionOperator(op);
1411 Fortran::evaluate::ExpressionAnalyzer ea{semanticsContext};
1412 for (const auto &accObject : objects.v) {
1413 llvm::SmallVector<mlir::Value> bounds;
1414 std::stringstream asFortran;
1415 mlir::Location operandLocation = genOperandLocation(converter, accObject);
1416 Fortran::semantics::Symbol &symbol = getSymbolFromAccObject(accObject);
1417 Fortran::semantics::MaybeExpr designator = Fortran::common::visit(
1418 [&](auto &&s) { return ea.Analyze(s); }, accObject.u);
1419 Fortran::lower::AddrAndBoundsInfo info =
1420 Fortran::lower::gatherDataOperandAddrAndBounds<
1421 mlir::acc::DataBoundsOp, mlir::acc::DataBoundsType>(
1422 converter, builder, semanticsContext, stmtCtx, symbol, designator,
1423 operandLocation, asFortran, bounds);
1424
1425 mlir::Type reductionTy = fir::unwrapRefType(info.addr.getType());
1426 if (auto seqTy = mlir::dyn_cast<fir::SequenceType>(reductionTy))
1427 reductionTy = seqTy.getEleTy();
1428
1429 if (!isSupportedReductionType(reductionTy))
1430 TODO(operandLocation, "reduction with unsupported type");
1431
1432 auto op = createDataEntryOp<mlir::acc::ReductionOp>(
1433 builder, operandLocation, info.addr, asFortran, bounds,
1434 /*structured=*/true, /*implicit=*/false,
1435 mlir::acc::DataClause::acc_reduction, info.addr.getType(), async,
1436 asyncDeviceTypes, asyncOnlyDeviceTypes);
1437 mlir::Type ty = op.getAccPtr().getType();
1438 if (!areAllBoundConstant(bounds) ||
1439 fir::isAssumedShape(info.addr.getType()) ||
1440 fir::isAllocatableOrPointerArray(info.addr.getType()))
1441 ty = info.addr.getType();
1442 std::string suffix =
1443 areAllBoundConstant(bounds) ? getBoundsString(bounds) : "";
1444 std::string recipeName = fir::getTypeAsString(
1445 ty, converter.getKindMap(),
1446 ("reduction_" + stringifyReductionOperator(mlirOp)).str() + suffix);
1447
1448 mlir::acc::ReductionRecipeOp recipe =
1449 Fortran::lower::createOrGetReductionRecipe(
1450 builder, recipeName, operandLocation, ty, mlirOp, bounds);
1451 reductionRecipes.push_back(mlir::SymbolRefAttr::get(
1452 builder.getContext(), recipe.getSymName().str()));
1453 reductionOperands.push_back(op.getAccPtr());
1454 }
1455 }
1456
1457 template <typename Op, typename Terminator>
1458 static Op
1459 createRegionOp(fir::FirOpBuilder &builder, mlir::Location loc,
1460 mlir::Location returnLoc, Fortran::lower::pft::Evaluation &eval,
1461 const llvm::SmallVectorImpl<mlir::Value> &operands,
1462 const llvm::SmallVectorImpl<int32_t> &operandSegments,
1463 bool outerCombined = false,
1464 llvm::SmallVector<mlir::Type> retTy = {},
1465 mlir::Value yieldValue = {}, mlir::TypeRange argsTy = {},
1466 llvm::SmallVector<mlir::Location> locs = {}) {
1467 Op op = builder.create<Op>(loc, retTy, operands);
1468 builder.createBlock(&op.getRegion(), op.getRegion().end(), argsTy, locs);
1469 mlir::Block &block = op.getRegion().back();
1470 builder.setInsertionPointToStart(&block);
1471
1472 op->setAttr(Op::getOperandSegmentSizeAttr(),
1473 builder.getDenseI32ArrayAttr(operandSegments));
1474
1475 // Place the insertion point to the start of the first block.
1476 builder.setInsertionPointToStart(&block);
1477
1478 // If it is an unstructured region and is not the outer region of a combined
1479 // construct, create empty blocks for all evaluations.
1480 if (eval.lowerAsUnstructured() && !outerCombined)
1481 Fortran::lower::createEmptyRegionBlocks<mlir::acc::TerminatorOp,
1482 mlir::acc::YieldOp>(
1483 builder, eval.getNestedEvaluations());
1484
1485 if (yieldValue) {
1486 if constexpr (std::is_same_v<Terminator, mlir::acc::YieldOp>) {
1487 Terminator yieldOp = builder.create<Terminator>(returnLoc, yieldValue);
1488 yieldValue.getDefiningOp()->moveBefore(yieldOp);
1489 } else {
1490 builder.create<Terminator>(returnLoc);
1491 }
1492 } else {
1493 builder.create<Terminator>(returnLoc);
1494 }
1495 builder.setInsertionPointToStart(&block);
1496 return op;
1497 }
1498
1499 static void genAsyncClause(Fortran::lower::AbstractConverter &converter,
1500 const Fortran::parser::AccClause::Async *asyncClause,
1501 mlir::Value &async, bool &addAsyncAttr,
1502 Fortran::lower::StatementContext &stmtCtx) {
1503 const auto &asyncClauseValue = asyncClause->v;
1504 if (asyncClauseValue) { // async has a value.
1505 async = fir::getBase(converter.genExprValue(
1506 *Fortran::semantics::GetExpr(*asyncClauseValue), stmtCtx));
1507 } else {
1508 addAsyncAttr = true;
1509 }
1510 }
1511
1512 static void
1513 genAsyncClause(Fortran::lower::AbstractConverter &converter,
1514 const Fortran::parser::AccClause::Async *asyncClause,
1515 llvm::SmallVector<mlir::Value> &async,
1516 llvm::SmallVector<mlir::Attribute> &asyncDeviceTypes,
1517 llvm::SmallVector<mlir::Attribute> &asyncOnlyDeviceTypes,
1518 llvm::SmallVector<mlir::Attribute> &deviceTypeAttrs,
1519 Fortran::lower::StatementContext &stmtCtx) {
1520 const auto &asyncClauseValue = asyncClause->v;
1521 if (asyncClauseValue) { // async has a value.
1522 mlir::Value asyncValue = fir::getBase(converter.genExprValue(
1523 *Fortran::semantics::GetExpr(*asyncClauseValue), stmtCtx));
1524 for (auto deviceTypeAttr : deviceTypeAttrs) {
1525 async.push_back(asyncValue);
1526 asyncDeviceTypes.push_back(deviceTypeAttr);
1527 }
1528 } else {
1529 for (auto deviceTypeAttr : deviceTypeAttrs)
1530 asyncOnlyDeviceTypes.push_back(deviceTypeAttr);
1531 }
1532 }
1533
1534 static mlir::acc::DeviceType
1535 getDeviceType(Fortran::common::OpenACCDeviceType device) {
1536 switch (device) {
1537 case Fortran::common::OpenACCDeviceType::Star:
1538 return mlir::acc::DeviceType::Star;
1539 case Fortran::common::OpenACCDeviceType::Default:
1540 return mlir::acc::DeviceType::Default;
1541 case Fortran::common::OpenACCDeviceType::Nvidia:
1542 return mlir::acc::DeviceType::Nvidia;
1543 case Fortran::common::OpenACCDeviceType::Radeon:
1544 return mlir::acc::DeviceType::Radeon;
1545 case Fortran::common::OpenACCDeviceType::Host:
1546 return mlir::acc::DeviceType::Host;
1547 case Fortran::common::OpenACCDeviceType::Multicore:
1548 return mlir::acc::DeviceType::Multicore;
1549 case Fortran::common::OpenACCDeviceType::None:
1550 return mlir::acc::DeviceType::None;
1551 }
1552 return mlir::acc::DeviceType::None;
1553 }
1554
1555 static void gatherDeviceTypeAttrs(
1556 fir::FirOpBuilder &builder,
1557 const Fortran::parser::AccClause::DeviceType *deviceTypeClause,
1558 llvm::SmallVector<mlir::Attribute> &deviceTypes) {
1559 const Fortran::parser::AccDeviceTypeExprList &deviceTypeExprList =
1560 deviceTypeClause->v;
1561 for (const auto &deviceTypeExpr : deviceTypeExprList.v)
1562 deviceTypes.push_back(mlir::acc::DeviceTypeAttr::get(
1563 builder.getContext(), getDeviceType(deviceTypeExpr.v)));
1564 }
1565
1566 static void genIfClause(Fortran::lower::AbstractConverter &converter,
1567 mlir::Location clauseLocation,
1568 const Fortran::parser::AccClause::If *ifClause,
1569 mlir::Value &ifCond,
1570 Fortran::lower::StatementContext &stmtCtx) {
1571 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
1572 mlir::Value cond = fir::getBase(converter.genExprValue(
1573 *Fortran::semantics::GetExpr(ifClause->v), stmtCtx, &clauseLocation));
1574 ifCond = firOpBuilder.createConvert(clauseLocation, firOpBuilder.getI1Type(),
1575 cond);
1576 }
1577
1578 static void genWaitClause(Fortran::lower::AbstractConverter &converter,
1579 const Fortran::parser::AccClause::Wait *waitClause,
1580 llvm::SmallVectorImpl<mlir::Value> &operands,
1581 mlir::Value &waitDevnum, bool &addWaitAttr,
1582 Fortran::lower::StatementContext &stmtCtx) {
1583 const auto &waitClauseValue = waitClause->v;
1584 if (waitClauseValue) { // wait has a value.
1585 const Fortran::parser::AccWaitArgument &waitArg = *waitClauseValue;
1586 const auto &waitList =
1587 std::get<std::list<Fortran::parser::ScalarIntExpr>>(waitArg.t);
1588 for (const Fortran::parser::ScalarIntExpr &value : waitList) {
1589 mlir::Value v = fir::getBase(
1590 converter.genExprValue(*Fortran::semantics::GetExpr(value), stmtCtx));
1591 operands.push_back(v);
1592 }
1593
1594 const auto &waitDevnumValue =
1595 std::get<std::optional<Fortran::parser::ScalarIntExpr>>(waitArg.t);
1596 if (waitDevnumValue)
1597 waitDevnum = fir::getBase(converter.genExprValue(
1598 *Fortran::semantics::GetExpr(*waitDevnumValue), stmtCtx));
1599 } else {
1600 addWaitAttr = true;
1601 }
1602 }
1603
1604 static void genWaitClauseWithDeviceType(
1605 Fortran::lower::AbstractConverter &converter,
1606 const Fortran::parser::AccClause::Wait *waitClause,
1607 llvm::SmallVector<mlir::Value> &waitOperands,
1608 llvm::SmallVector<mlir::Attribute> &waitOperandsDeviceTypes,
1609 llvm::SmallVector<mlir::Attribute> &waitOnlyDeviceTypes,
1610 llvm::SmallVector<bool> &hasDevnums,
1611 llvm::SmallVector<int32_t> &waitOperandsSegments,
1612 llvm::SmallVector<mlir::Attribute> deviceTypeAttrs,
1613 Fortran::lower::StatementContext &stmtCtx) {
1614 const auto &waitClauseValue = waitClause->v;
1615 if (waitClauseValue) { // wait has a value.
1616 llvm::SmallVector<mlir::Value> waitValues;
1617
1618 const Fortran::parser::AccWaitArgument &waitArg = *waitClauseValue;
1619 const auto &waitDevnumValue =
1620 std::get<std::optional<Fortran::parser::ScalarIntExpr>>(waitArg.t);
1621 bool hasDevnum = false;
1622 if (waitDevnumValue) {
1623 waitValues.push_back(fir::getBase(converter.genExprValue(
1624 *Fortran::semantics::GetExpr(*waitDevnumValue), stmtCtx)));
1625 hasDevnum = true;
1626 }
1627
1628 const auto &waitList =
1629 std::get<std::list<Fortran::parser::ScalarIntExpr>>(waitArg.t);
1630 for (const Fortran::parser::ScalarIntExpr &value : waitList) {
1631 waitValues.push_back(fir::getBase(converter.genExprValue(
1632 *Fortran::semantics::GetExpr(value), stmtCtx)));
1633 }
1634
1635 for (auto deviceTypeAttr : deviceTypeAttrs) {
1636 for (auto value : waitValues)
1637 waitOperands.push_back(value);
1638 waitOperandsDeviceTypes.push_back(deviceTypeAttr);
1639 waitOperandsSegments.push_back(waitValues.size());
1640 hasDevnums.push_back(hasDevnum);
1641 }
1642 } else {
1643 for (auto deviceTypeAttr : deviceTypeAttrs)
1644 waitOnlyDeviceTypes.push_back(deviceTypeAttr);
1645 }
1646 }
1647
1648 mlir::Type getTypeFromIvTypeSize(fir::FirOpBuilder &builder,
1649 const Fortran::semantics::Symbol &ivSym) {
1650 std::size_t ivTypeSize = ivSym.size();
1651 if (ivTypeSize == 0)
1652 llvm::report_fatal_error("unexpected induction variable size");
1653 // ivTypeSize is in bytes and IntegerType needs to be in bits.
1654 return builder.getIntegerType(ivTypeSize * 8);
1655 }
1656
1657 static void privatizeIv(Fortran::lower::AbstractConverter &converter,
1658 const Fortran::semantics::Symbol &sym,
1659 mlir::Location loc,
1660 llvm::SmallVector<mlir::Type> &ivTypes,
1661 llvm::SmallVector<mlir::Location> &ivLocs,
1662 llvm::SmallVector<mlir::Value> &privateOperands,
1663 llvm::SmallVector<mlir::Value> &ivPrivate,
1664 llvm::SmallVector<mlir::Attribute> &privatizations,
1665 bool isDoConcurrent = false) {
1666 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1667
1668 mlir::Type ivTy = getTypeFromIvTypeSize(builder, sym);
1669 ivTypes.push_back(ivTy);
1670 ivLocs.push_back(loc);
1671 mlir::Value ivValue = converter.getSymbolAddress(sym);
1672 if (!ivValue && isDoConcurrent) {
1673 // DO CONCURRENT induction variables are not mapped yet since they are local
1674 // to the DO CONCURRENT scope.
1675 mlir::OpBuilder::InsertPoint insPt = builder.saveInsertionPoint();
1676 builder.setInsertionPointToStart(builder.getAllocaBlock());
1677 ivValue = builder.createTemporaryAlloc(loc, ivTy, toStringRef(sym.name()));
1678 builder.restoreInsertionPoint(insPt);
1679 }
1680
1681 std::string recipeName =
1682 fir::getTypeAsString(ivValue.getType(), converter.getKindMap(),
1683 Fortran::lower::privatizationRecipePrefix);
1684 auto recipe = Fortran::lower::createOrGetPrivateRecipe(
1685 builder, recipeName, loc, ivValue.getType());
1686
1687 std::stringstream asFortran;
1688 auto op = createDataEntryOp<mlir::acc::PrivateOp>(
1689 builder, loc, ivValue, asFortran, {}, true, /*implicit=*/true,
1690 mlir::acc::DataClause::acc_private, ivValue.getType(),
1691 /*async=*/{}, /*asyncDeviceTypes=*/{}, /*asyncOnlyDeviceTypes=*/{});
1692
1693 privateOperands.push_back(op.getAccPtr());
1694 privatizations.push_back(mlir::SymbolRefAttr::get(builder.getContext(),
1695 recipe.getSymName().str()));
1696
1697 // Map the new private iv to its symbol for the scope of the loop. bindSymbol
1698 // might create a hlfir.declare op, if so, we map its result in order to
1699 // use the sym value in the scope.
1700 converter.bindSymbol(sym, op.getAccPtr());
1701 auto privateValue = converter.getSymbolAddress(sym);
1702 if (auto declareOp =
1703 mlir::dyn_cast<hlfir::DeclareOp>(privateValue.getDefiningOp()))
1704 privateValue = declareOp.getResults()[0];
1705 ivPrivate.push_back(privateValue);
1706 }
1707
1708 static mlir::acc::LoopOp createLoopOp(
1709 Fortran::lower::AbstractConverter &converter,
1710 mlir::Location currentLocation,
1711 Fortran::semantics::SemanticsContext &semanticsContext,
1712 Fortran::lower::StatementContext &stmtCtx,
1713 const Fortran::parser::DoConstruct &outerDoConstruct,
1714 Fortran::lower::pft::Evaluation &eval,
1715 const Fortran::parser::AccClauseList &accClauseList,
1716 std::optional<mlir::acc::CombinedConstructsType> combinedConstructs =
1717 std::nullopt,
1718 bool needEarlyReturnHandling = false) {
1719 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
1720 llvm::SmallVector<mlir::Value> tileOperands, privateOperands, ivPrivate,
1721 reductionOperands, cacheOperands, vectorOperands, workerNumOperands,
1722 gangOperands, lowerbounds, upperbounds, steps;
1723 llvm::SmallVector<mlir::Attribute> privatizations, reductionRecipes;
1724 llvm::SmallVector<int32_t> tileOperandsSegments, gangOperandsSegments;
1725 llvm::SmallVector<int64_t> collapseValues;
1726
1727 llvm::SmallVector<mlir::Attribute> gangArgTypes;
1728 llvm::SmallVector<mlir::Attribute> seqDeviceTypes, independentDeviceTypes,
1729 autoDeviceTypes, vectorOperandsDeviceTypes, workerNumOperandsDeviceTypes,
1730 vectorDeviceTypes, workerNumDeviceTypes, tileOperandsDeviceTypes,
1731 collapseDeviceTypes, gangDeviceTypes, gangOperandsDeviceTypes;
1732
1733 // device_type attribute is set to `none` until a device_type clause is
1734 // encountered.
1735 llvm::SmallVector<mlir::Attribute> crtDeviceTypes;
1736 crtDeviceTypes.push_back(mlir::acc::DeviceTypeAttr::get(
1737 builder.getContext(), mlir::acc::DeviceType::None));
1738
1739 llvm::SmallVector<mlir::Type> ivTypes;
1740 llvm::SmallVector<mlir::Location> ivLocs;
1741 llvm::SmallVector<bool> inclusiveBounds;
1742
1743 llvm::SmallVector<mlir::Location> locs;
1744 locs.push_back(currentLocation); // Location of the directive
1745 Fortran::lower::pft::Evaluation *crtEval = &eval.getFirstNestedEvaluation();
1746 bool isDoConcurrent = outerDoConstruct.IsDoConcurrent();
1747 if (isDoConcurrent) {
1748 locs.push_back(converter.genLocation(
1749 Fortran::parser::FindSourceLocation(outerDoConstruct)));
1750 const Fortran::parser::LoopControl *loopControl =
1751 &*outerDoConstruct.GetLoopControl();
1752 const auto &concurrent =
1753 std::get<Fortran::parser::LoopControl::Concurrent>(loopControl->u);
1754 if (!std::get<std::list<Fortran::parser::LocalitySpec>>(concurrent.t)
1755 .empty())
1756 TODO(currentLocation, "DO CONCURRENT with locality spec");
1757
1758 const auto &concurrentHeader =
1759 std::get<Fortran::parser::ConcurrentHeader>(concurrent.t);
1760 const auto &controls =
1761 std::get<std::list<Fortran::parser::ConcurrentControl>>(
1762 concurrentHeader.t);
1763 for (const auto &control : controls) {
1764 lowerbounds.push_back(fir::getBase(converter.genExprValue(
1765 *Fortran::semantics::GetExpr(std::get<1>(control.t)), stmtCtx)));
1766 upperbounds.push_back(fir::getBase(converter.genExprValue(
1767 *Fortran::semantics::GetExpr(std::get<2>(control.t)), stmtCtx)));
1768 if (const auto &expr =
1769 std::get<std::optional<Fortran::parser::ScalarIntExpr>>(
1770 control.t))
1771 steps.push_back(fir::getBase(converter.genExprValue(
1772 *Fortran::semantics::GetExpr(*expr), stmtCtx)));
1773 else // If `step` is not present, assume it is `1`.
1774 steps.push_back(builder.createIntegerConstant(
1775 currentLocation, upperbounds[upperbounds.size() - 1].getType(), 1));
1776
1777 const auto &name = std::get<Fortran::parser::Name>(control.t);
1778 privatizeIv(converter, *name.symbol, currentLocation, ivTypes, ivLocs,
1779 privateOperands, ivPrivate, privatizations, isDoConcurrent);
1780
1781 inclusiveBounds.push_back(true);
1782 }
1783 } else {
1784 int64_t collapseValue = Fortran::lower::getCollapseValue(accClauseList);
1785 for (unsigned i = 0; i < collapseValue; ++i) {
1786 const Fortran::parser::LoopControl *loopControl;
1787 if (i == 0) {
1788 loopControl = &*outerDoConstruct.GetLoopControl();
1789 locs.push_back(converter.genLocation(
1790 Fortran::parser::FindSourceLocation(outerDoConstruct)));
1791 } else {
1792 auto *doCons = crtEval->getIf<Fortran::parser::DoConstruct>();
1793 assert(doCons && "expect do construct");
1794 loopControl = &*doCons->GetLoopControl();
1795 locs.push_back(converter.genLocation(
1796 Fortran::parser::FindSourceLocation(*doCons)));
1797 }
1798
1799 const Fortran::parser::LoopControl::Bounds *bounds =
1800 std::get_if<Fortran::parser::LoopControl::Bounds>(&loopControl->u);
1801 assert(bounds && "Expected bounds on the loop construct");
1802 lowerbounds.push_back(fir::getBase(converter.genExprValue(
1803 *Fortran::semantics::GetExpr(bounds->lower), stmtCtx)));
1804 upperbounds.push_back(fir::getBase(converter.genExprValue(
1805 *Fortran::semantics::GetExpr(bounds->upper), stmtCtx)));
1806 if (bounds->step)
1807 steps.push_back(fir::getBase(converter.genExprValue(
1808 *Fortran::semantics::GetExpr(bounds->step), stmtCtx)));
1809 else // If `step` is not present, assume it is `1`.
1810 steps.push_back(builder.createIntegerConstant(
1811 currentLocation, upperbounds[upperbounds.size() - 1].getType(), 1));
1812
1813 Fortran::semantics::Symbol &ivSym =
1814 bounds->name.thing.symbol->GetUltimate();
1815 privatizeIv(converter, ivSym, currentLocation, ivTypes, ivLocs,
1816 privateOperands, ivPrivate, privatizations);
1817
1818 inclusiveBounds.push_back(true);
1819
1820 if (i < collapseValue - 1)
1821 crtEval = &*std::next(crtEval->getNestedEvaluations().begin());
1822 }
1823 }
1824
1825 for (const Fortran::parser::AccClause &clause : accClauseList.v) {
1826 mlir::Location clauseLocation = converter.genLocation(clause.source);
1827 if (const auto *gangClause =
1828 std::get_if<Fortran::parser::AccClause::Gang>(&clause.u)) {
1829 if (gangClause->v) {
1830 const Fortran::parser::AccGangArgList &x = *gangClause->v;
1831 mlir::SmallVector<mlir::Value> gangValues;
1832 mlir::SmallVector<mlir::Attribute> gangArgs;
1833 for (const Fortran::parser::AccGangArg &gangArg : x.v) {
1834 if (const auto *num =
1835 std::get_if<Fortran::parser::AccGangArg::Num>(&gangArg.u)) {
1836 gangValues.push_back(fir::getBase(converter.genExprValue(
1837 *Fortran::semantics::GetExpr(num->v), stmtCtx)));
1838 gangArgs.push_back(mlir::acc::GangArgTypeAttr::get(
1839 builder.getContext(), mlir::acc::GangArgType::Num));
1840 } else if (const auto *staticArg =
1841 std::get_if<Fortran::parser::AccGangArg::Static>(
1842 &gangArg.u)) {
1843 const Fortran::parser::AccSizeExpr &sizeExpr = staticArg->v;
1844 if (sizeExpr.v) {
1845 gangValues.push_back(fir::getBase(converter.genExprValue(
1846 *Fortran::semantics::GetExpr(*sizeExpr.v), stmtCtx)));
1847 } else {
1848 // * was passed as value and will be represented as a special
1849 // constant.
1850 gangValues.push_back(builder.createIntegerConstant(
1851 clauseLocation, builder.getIndexType(), starCst));
1852 }
1853 gangArgs.push_back(mlir::acc::GangArgTypeAttr::get(
1854 builder.getContext(), mlir::acc::GangArgType::Static));
1855 } else if (const auto *dim =
1856 std::get_if<Fortran::parser::AccGangArg::Dim>(
1857 &gangArg.u)) {
1858 gangValues.push_back(fir::getBase(converter.genExprValue(
1859 *Fortran::semantics::GetExpr(dim->v), stmtCtx)));
1860 gangArgs.push_back(mlir::acc::GangArgTypeAttr::get(
1861 builder.getContext(), mlir::acc::GangArgType::Dim));
1862 }
1863 }
1864 for (auto crtDeviceTypeAttr : crtDeviceTypes) {
1865 for (const auto &pair : llvm::zip(gangValues, gangArgs)) {
1866 gangOperands.push_back(std::get<0>(pair));
1867 gangArgTypes.push_back(std::get<1>(pair));
1868 }
1869 gangOperandsSegments.push_back(gangValues.size());
1870 gangOperandsDeviceTypes.push_back(crtDeviceTypeAttr);
1871 }
1872 } else {
1873 for (auto crtDeviceTypeAttr : crtDeviceTypes)
1874 gangDeviceTypes.push_back(crtDeviceTypeAttr);
1875 }
1876 } else if (const auto *workerClause =
1877 std::get_if<Fortran::parser::AccClause::Worker>(&clause.u)) {
1878 if (workerClause->v) {
1879 mlir::Value workerNumValue = fir::getBase(converter.genExprValue(
1880 *Fortran::semantics::GetExpr(*workerClause->v), stmtCtx));
1881 for (auto crtDeviceTypeAttr : crtDeviceTypes) {
1882 workerNumOperands.push_back(workerNumValue);
1883 workerNumOperandsDeviceTypes.push_back(crtDeviceTypeAttr);
1884 }
1885 } else {
1886 for (auto crtDeviceTypeAttr : crtDeviceTypes)
1887 workerNumDeviceTypes.push_back(crtDeviceTypeAttr);
1888 }
1889 } else if (const auto *vectorClause =
1890 std::get_if<Fortran::parser::AccClause::Vector>(&clause.u)) {
1891 if (vectorClause->v) {
1892 mlir::Value vectorValue = fir::getBase(converter.genExprValue(
1893 *Fortran::semantics::GetExpr(*vectorClause->v), stmtCtx));
1894 for (auto crtDeviceTypeAttr : crtDeviceTypes) {
1895 vectorOperands.push_back(vectorValue);
1896 vectorOperandsDeviceTypes.push_back(crtDeviceTypeAttr);
1897 }
1898 } else {
1899 for (auto crtDeviceTypeAttr : crtDeviceTypes)
1900 vectorDeviceTypes.push_back(crtDeviceTypeAttr);
1901 }
1902 } else if (const auto *tileClause =
1903 std::get_if<Fortran::parser::AccClause::Tile>(&clause.u)) {
1904 const Fortran::parser::AccTileExprList &accTileExprList = tileClause->v;
1905 llvm::SmallVector<mlir::Value> tileValues;
1906 for (const auto &accTileExpr : accTileExprList.v) {
1907 const auto &expr =
1908 std::get<std::optional<Fortran::parser::ScalarIntConstantExpr>>(
1909 accTileExpr.t);
1910 if (expr) {
1911 tileValues.push_back(fir::getBase(converter.genExprValue(
1912 *Fortran::semantics::GetExpr(*expr), stmtCtx)));
1913 } else {
1914 // * was passed as value and will be represented as a special
1915 // constant.
1916 mlir::Value tileStar = builder.createIntegerConstant(
1917 clauseLocation, builder.getIntegerType(32), starCst);
1918 tileValues.push_back(tileStar);
1919 }
1920 }
1921 for (auto crtDeviceTypeAttr : crtDeviceTypes) {
1922 for (auto value : tileValues)
1923 tileOperands.push_back(value);
1924 tileOperandsDeviceTypes.push_back(crtDeviceTypeAttr);
1925 tileOperandsSegments.push_back(tileValues.size());
1926 }
1927 } else if (const auto *privateClause =
1928 std::get_if<Fortran::parser::AccClause::Private>(
1929 &clause.u)) {
1930 genPrivatizations<mlir::acc::PrivateRecipeOp>(
1931 privateClause->v, converter, semanticsContext, stmtCtx,
1932 privateOperands, privatizations, /*async=*/{},
1933 /*asyncDeviceTypes=*/{}, /*asyncOnlyDeviceTypes=*/{});
1934 } else if (const auto *reductionClause =
1935 std::get_if<Fortran::parser::AccClause::Reduction>(
1936 &clause.u)) {
1937 genReductions(reductionClause->v, converter, semanticsContext, stmtCtx,
1938 reductionOperands, reductionRecipes, /*async=*/{},
1939 /*asyncDeviceTypes=*/{}, /*asyncOnlyDeviceTypes=*/{});
1940 } else if (std::get_if<Fortran::parser::AccClause::Seq>(&clause.u)) {
1941 for (auto crtDeviceTypeAttr : crtDeviceTypes)
1942 seqDeviceTypes.push_back(crtDeviceTypeAttr);
1943 } else if (std::get_if<Fortran::parser::AccClause::Independent>(
1944 &clause.u)) {
1945 for (auto crtDeviceTypeAttr : crtDeviceTypes)
1946 independentDeviceTypes.push_back(crtDeviceTypeAttr);
1947 } else if (std::get_if<Fortran::parser::AccClause::Auto>(&clause.u)) {
1948 for (auto crtDeviceTypeAttr : crtDeviceTypes)
1949 autoDeviceTypes.push_back(crtDeviceTypeAttr);
1950 } else if (const auto *deviceTypeClause =
1951 std::get_if<Fortran::parser::AccClause::DeviceType>(
1952 &clause.u)) {
1953 crtDeviceTypes.clear();
1954 gatherDeviceTypeAttrs(builder, deviceTypeClause, crtDeviceTypes);
1955 } else if (const auto *collapseClause =
1956 std::get_if<Fortran::parser::AccClause::Collapse>(
1957 &clause.u)) {
1958 const Fortran::parser::AccCollapseArg &arg = collapseClause->v;
1959 const auto &force = std::get<bool>(arg.t);
1960 if (force)
1961 TODO(clauseLocation, "OpenACC collapse force modifier");
1962
1963 const auto &intExpr =
1964 std::get<Fortran::parser::ScalarIntConstantExpr>(arg.t);
1965 const auto *expr = Fortran::semantics::GetExpr(intExpr);
1966 const std::optional<int64_t> collapseValue =
1967 Fortran::evaluate::ToInt64(*expr);
1968 assert(collapseValue && "expect integer value for the collapse clause");
1969
1970 for (auto crtDeviceTypeAttr : crtDeviceTypes) {
1971 collapseValues.push_back(*collapseValue);
1972 collapseDeviceTypes.push_back(crtDeviceTypeAttr);
1973 }
1974 }
1975 }
1976
1977 // Prepare the operand segment size attribute and the operands value range.
1978 llvm::SmallVector<mlir::Value> operands;
1979 llvm::SmallVector<int32_t> operandSegments;
1980 addOperands(operands, operandSegments, lowerbounds);
1981 addOperands(operands, operandSegments, upperbounds);
1982 addOperands(operands, operandSegments, steps);
1983 addOperands(operands, operandSegments, gangOperands);
1984 addOperands(operands, operandSegments, workerNumOperands);
1985 addOperands(operands, operandSegments, vectorOperands);
1986 addOperands(operands, operandSegments, tileOperands);
1987 addOperands(operands, operandSegments, cacheOperands);
1988 addOperands(operands, operandSegments, privateOperands);
1989 addOperands(operands, operandSegments, reductionOperands);
1990
1991 llvm::SmallVector<mlir::Type> retTy;
1992 mlir::Value yieldValue;
1993 if (needEarlyReturnHandling) {
1994 mlir::Type i1Ty = builder.getI1Type();
1995 yieldValue = builder.createIntegerConstant(currentLocation, i1Ty, 0);
1996 retTy.push_back(i1Ty);
1997 }
1998
1999 auto loopOp = createRegionOp<mlir::acc::LoopOp, mlir::acc::YieldOp>(
2000 builder, builder.getFusedLoc(locs), currentLocation, eval, operands,
2001 operandSegments, /*outerCombined=*/false, retTy, yieldValue, ivTypes,
2002 ivLocs);
2003
2004 for (auto [arg, value] : llvm::zip(
2005 loopOp.getLoopRegions().front()->front().getArguments(), ivPrivate))
2006 builder.create<fir::StoreOp>(currentLocation, arg, value);
2007
2008 loopOp.setInclusiveUpperbound(inclusiveBounds);
2009
2010 if (!gangDeviceTypes.empty())
2011 loopOp.setGangAttr(builder.getArrayAttr(gangDeviceTypes));
2012 if (!gangArgTypes.empty())
2013 loopOp.setGangOperandsArgTypeAttr(builder.getArrayAttr(gangArgTypes));
2014 if (!gangOperandsSegments.empty())
2015 loopOp.setGangOperandsSegmentsAttr(
2016 builder.getDenseI32ArrayAttr(gangOperandsSegments));
2017 if (!gangOperandsDeviceTypes.empty())
2018 loopOp.setGangOperandsDeviceTypeAttr(
2019 builder.getArrayAttr(gangOperandsDeviceTypes));
2020
2021 if (!workerNumDeviceTypes.empty())
2022 loopOp.setWorkerAttr(builder.getArrayAttr(workerNumDeviceTypes));
2023 if (!workerNumOperandsDeviceTypes.empty())
2024 loopOp.setWorkerNumOperandsDeviceTypeAttr(
2025 builder.getArrayAttr(workerNumOperandsDeviceTypes));
2026
2027 if (!vectorDeviceTypes.empty())
2028 loopOp.setVectorAttr(builder.getArrayAttr(vectorDeviceTypes));
2029 if (!vectorOperandsDeviceTypes.empty())
2030 loopOp.setVectorOperandsDeviceTypeAttr(
2031 builder.getArrayAttr(vectorOperandsDeviceTypes));
2032
2033 if (!tileOperandsDeviceTypes.empty())
2034 loopOp.setTileOperandsDeviceTypeAttr(
2035 builder.getArrayAttr(tileOperandsDeviceTypes));
2036 if (!tileOperandsSegments.empty())
2037 loopOp.setTileOperandsSegmentsAttr(
2038 builder.getDenseI32ArrayAttr(tileOperandsSegments));
2039
2040 if (!seqDeviceTypes.empty())
2041 loopOp.setSeqAttr(builder.getArrayAttr(seqDeviceTypes));
2042 if (!independentDeviceTypes.empty())
2043 loopOp.setIndependentAttr(builder.getArrayAttr(independentDeviceTypes));
2044 if (!autoDeviceTypes.empty())
2045 loopOp.setAuto_Attr(builder.getArrayAttr(autoDeviceTypes));
2046
2047 if (!privatizations.empty())
2048 loopOp.setPrivatizationsAttr(
2049 mlir::ArrayAttr::get(builder.getContext(), privatizations));
2050
2051 if (!reductionRecipes.empty())
2052 loopOp.setReductionRecipesAttr(
2053 mlir::ArrayAttr::get(builder.getContext(), reductionRecipes));
2054
2055 if (!collapseValues.empty())
2056 loopOp.setCollapseAttr(builder.getI64ArrayAttr(collapseValues));
2057 if (!collapseDeviceTypes.empty())
2058 loopOp.setCollapseDeviceTypeAttr(builder.getArrayAttr(collapseDeviceTypes));
2059
2060 if (combinedConstructs)
2061 loopOp.setCombinedAttr(mlir::acc::CombinedConstructsTypeAttr::get(
2062 builder.getContext(), *combinedConstructs));
2063
2064 return loopOp;
2065 }
2066
2067 static bool hasEarlyReturn(Fortran::lower::pft::Evaluation &eval) {
2068 bool hasReturnStmt = false;
2069 for (auto &e : eval.getNestedEvaluations()) {
2070 e.visit(Fortran::common::visitors{
2071 [&](const Fortran::parser::ReturnStmt &) { hasReturnStmt = true; },
2072 [&](const auto &s) {},
2073 });
2074 if (e.hasNestedEvaluations())
2075 hasReturnStmt = hasEarlyReturn(e);
2076 }
2077 return hasReturnStmt;
2078 }
2079
2080 static mlir::Value
2081 genACC(Fortran::lower::AbstractConverter &converter,
2082 Fortran::semantics::SemanticsContext &semanticsContext,
2083 Fortran::lower::pft::Evaluation &eval,
2084 const Fortran::parser::OpenACCLoopConstruct &loopConstruct) {
2085
2086 const auto &beginLoopDirective =
2087 std::get<Fortran::parser::AccBeginLoopDirective>(loopConstruct.t);
2088 const auto &loopDirective =
2089 std::get<Fortran::parser::AccLoopDirective>(beginLoopDirective.t);
2090
2091 bool needEarlyExitHandling = false;
2092 if (eval.lowerAsUnstructured())
2093 needEarlyExitHandling = hasEarlyReturn(eval);
2094
2095 mlir::Location currentLocation =
2096 converter.genLocation(beginLoopDirective.source);
2097 Fortran::lower::StatementContext stmtCtx;
2098
2099 assert(loopDirective.v == llvm::acc::ACCD_loop &&
2100 "Unsupported OpenACC loop construct");
2101 (void)loopDirective;
2102
2103 const auto &accClauseList =
2104 std::get<Fortran::parser::AccClauseList>(beginLoopDirective.t);
2105 const auto &outerDoConstruct =
2106 std::get<std::optional<Fortran::parser::DoConstruct>>(loopConstruct.t);
2107 auto loopOp = createLoopOp(converter, currentLocation, semanticsContext,
2108 stmtCtx, *outerDoConstruct, eval, accClauseList,
2109 /*combinedConstructs=*/{}, needEarlyExitHandling);
2110 if (needEarlyExitHandling)
2111 return loopOp.getResult(0);
2112
2113 return mlir::Value{};
2114 }
2115
2116 template <typename Op, typename Clause>
2117 static void genDataOperandOperationsWithModifier(
2118 const Clause *x, Fortran::lower::AbstractConverter &converter,
2119 Fortran::semantics::SemanticsContext &semanticsContext,
2120 Fortran::lower::StatementContext &stmtCtx,
2121 Fortran::parser::AccDataModifier::Modifier mod,
2122 llvm::SmallVectorImpl<mlir::Value> &dataClauseOperands,
2123 const mlir::acc::DataClause clause,
2124 const mlir::acc::DataClause clauseWithModifier,
2125 llvm::ArrayRef<mlir::Value> async,
2126 llvm::ArrayRef<mlir::Attribute> asyncDeviceTypes,
2127 llvm::ArrayRef<mlir::Attribute> asyncOnlyDeviceTypes,
2128 bool setDeclareAttr = false) {
2129 const Fortran::parser::AccObjectListWithModifier &listWithModifier = x->v;
2130 const auto &accObjectList =
2131 std::get<Fortran::parser::AccObjectList>(listWithModifier.t);
2132 const auto &modifier =
2133 std::get<std::optional<Fortran::parser::AccDataModifier>>(
2134 listWithModifier.t);
2135 mlir::acc::DataClause dataClause =
2136 (modifier && (*modifier).v == mod) ? clauseWithModifier : clause;
2137 genDataOperandOperations<Op>(accObjectList, converter, semanticsContext,
2138 stmtCtx, dataClauseOperands, dataClause,
2139 /*structured=*/true, /*implicit=*/false, async,
2140 asyncDeviceTypes, asyncOnlyDeviceTypes,
2141 setDeclareAttr);
2142 }
2143
2144 template <typename Op>
2145 static Op createComputeOp(
2146 Fortran::lower::AbstractConverter &converter,
2147 mlir::Location currentLocation, Fortran::lower::pft::Evaluation &eval,
2148 Fortran::semantics::SemanticsContext &semanticsContext,
2149 Fortran::lower::StatementContext &stmtCtx,
2150 const Fortran::parser::AccClauseList &accClauseList,
2151 std::optional<mlir::acc::CombinedConstructsType> combinedConstructs =
2152 std::nullopt) {
2153
2154 // Parallel operation operands
2155 mlir::Value ifCond;
2156 mlir::Value selfCond;
2157 llvm::SmallVector<mlir::Value> waitOperands, attachEntryOperands,
2158 copyEntryOperands, copyoutEntryOperands, createEntryOperands,
2159 dataClauseOperands, numGangs, numWorkers, vectorLength, async;
2160 llvm::SmallVector<mlir::Attribute> numGangsDeviceTypes, numWorkersDeviceTypes,
2161 vectorLengthDeviceTypes, asyncDeviceTypes, asyncOnlyDeviceTypes,
2162 waitOperandsDeviceTypes, waitOnlyDeviceTypes;
2163 llvm::SmallVector<int32_t> numGangsSegments, waitOperandsSegments;
2164 llvm::SmallVector<bool> hasWaitDevnums;
2165
2166 llvm::SmallVector<mlir::Value> reductionOperands, privateOperands,
2167 firstprivateOperands;
2168 llvm::SmallVector<mlir::Attribute> privatizations, firstPrivatizations,
2169 reductionRecipes;
2170
2171 // Self clause has optional values but can be present with
2172 // no value as well. When there is no value, the op has an attribute to
2173 // represent the clause.
2174 bool addSelfAttr = false;
2175
2176 bool hasDefaultNone = false;
2177 bool hasDefaultPresent = false;
2178
2179 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
2180
2181 // device_type attribute is set to `none` until a device_type clause is
2182 // encountered.
2183 llvm::SmallVector<mlir::Attribute> crtDeviceTypes;
2184 auto crtDeviceTypeAttr = mlir::acc::DeviceTypeAttr::get(
2185 builder.getContext(), mlir::acc::DeviceType::None);
2186 crtDeviceTypes.push_back(crtDeviceTypeAttr);
2187
2188 // Lower clauses values mapped to operands and array attributes.
2189 // Keep track of each group of operands separately as clauses can appear
2190 // more than once.
2191
2192 // Process the clauses that may have a specified device_type first.
2193 for (const Fortran::parser::AccClause &clause : accClauseList.v) {
2194 if (const auto *asyncClause =
2195 std::get_if<Fortran::parser::AccClause::Async>(&clause.u)) {
2196 genAsyncClause(converter, asyncClause, async, asyncDeviceTypes,
2197 asyncOnlyDeviceTypes, crtDeviceTypes, stmtCtx);
2198 } else if (const auto *waitClause =
2199 std::get_if<Fortran::parser::AccClause::Wait>(&clause.u)) {
2200 genWaitClauseWithDeviceType(converter, waitClause, waitOperands,
2201 waitOperandsDeviceTypes, waitOnlyDeviceTypes,
2202 hasWaitDevnums, waitOperandsSegments,
2203 crtDeviceTypes, stmtCtx);
2204 } else if (const auto *numGangsClause =
2205 std::get_if<Fortran::parser::AccClause::NumGangs>(
2206 &clause.u)) {
2207 llvm::SmallVector<mlir::Value> numGangValues;
2208 for (const Fortran::parser::ScalarIntExpr &expr : numGangsClause->v)
2209 numGangValues.push_back(fir::getBase(converter.genExprValue(
2210 *Fortran::semantics::GetExpr(expr), stmtCtx)));
2211 for (auto crtDeviceTypeAttr : crtDeviceTypes) {
2212 for (auto value : numGangValues)
2213 numGangs.push_back(value);
2214 numGangsDeviceTypes.push_back(crtDeviceTypeAttr);
2215 numGangsSegments.push_back(numGangValues.size());
2216 }
2217 } else if (const auto *numWorkersClause =
2218 std::get_if<Fortran::parser::AccClause::NumWorkers>(
2219 &clause.u)) {
2220 mlir::Value numWorkerValue = fir::getBase(converter.genExprValue(
2221 *Fortran::semantics::GetExpr(numWorkersClause->v), stmtCtx));
2222 for (auto crtDeviceTypeAttr : crtDeviceTypes) {
2223 numWorkers.push_back(numWorkerValue);
2224 numWorkersDeviceTypes.push_back(crtDeviceTypeAttr);
2225 }
2226 } else if (const auto *vectorLengthClause =
2227 std::get_if<Fortran::parser::AccClause::VectorLength>(
2228 &clause.u)) {
2229 mlir::Value vectorLengthValue = fir::getBase(converter.genExprValue(
2230 *Fortran::semantics::GetExpr(vectorLengthClause->v), stmtCtx));
2231 for (auto crtDeviceTypeAttr : crtDeviceTypes) {
2232 vectorLength.push_back(vectorLengthValue);
2233 vectorLengthDeviceTypes.push_back(crtDeviceTypeAttr);
2234 }
2235 } else if (const auto *deviceTypeClause =
2236 std::get_if<Fortran::parser::AccClause::DeviceType>(
2237 &clause.u)) {
2238 crtDeviceTypes.clear();
2239 gatherDeviceTypeAttrs(builder, deviceTypeClause, crtDeviceTypes);
2240 }
2241 }
2242
2243 // Process the clauses independent of device_type.
2244 for (const Fortran::parser::AccClause &clause : accClauseList.v) {
2245 mlir::Location clauseLocation = converter.genLocation(clause.source);
2246 if (const auto *ifClause =
2247 std::get_if<Fortran::parser::AccClause::If>(&clause.u)) {
2248 genIfClause(converter, clauseLocation, ifClause, ifCond, stmtCtx);
2249 } else if (const auto *selfClause =
2250 std::get_if<Fortran::parser::AccClause::Self>(&clause.u)) {
2251 const std::optional<Fortran::parser::AccSelfClause> &accSelfClause =
2252 selfClause->v;
2253 if (accSelfClause) {
2254 if (const auto *optCondition =
2255 std::get_if<std::optional<Fortran::parser::ScalarLogicalExpr>>(
2256 &(*accSelfClause).u)) {
2257 if (*optCondition) {
2258 mlir::Value cond = fir::getBase(converter.genExprValue(
2259 *Fortran::semantics::GetExpr(*optCondition), stmtCtx));
2260 selfCond = builder.createConvert(clauseLocation,
2261 builder.getI1Type(), cond);
2262 }
2263 } else if (const auto *accClauseList =
2264 std::get_if<Fortran::parser::AccObjectList>(
2265 &(*accSelfClause).u)) {
2266 // TODO This would be nicer to be done in canonicalization step.
2267 if (accClauseList->v.size() == 1) {
2268 const auto &accObject = accClauseList->v.front();
2269 if (const auto *designator =
2270 std::get_if<Fortran::parser::Designator>(&accObject.u)) {
2271 if (const auto *name =
2272 Fortran::semantics::getDesignatorNameIfDataRef(
2273 *designator)) {
2274 auto cond = converter.getSymbolAddress(*name->symbol);
2275 selfCond = builder.createConvert(clauseLocation,
2276 builder.getI1Type(), cond);
2277 }
2278 }
2279 }
2280 }
2281 } else {
2282 addSelfAttr = true;
2283 }
2284 } else if (const auto *copyClause =
2285 std::get_if<Fortran::parser::AccClause::Copy>(&clause.u)) {
2286 auto crtDataStart = dataClauseOperands.size();
2287 genDataOperandOperations<mlir::acc::CopyinOp>(
2288 copyClause->v, converter, semanticsContext, stmtCtx,
2289 dataClauseOperands, mlir::acc::DataClause::acc_copy,
2290 /*structured=*/true, /*implicit=*/false, async, asyncDeviceTypes,
2291 asyncOnlyDeviceTypes);
2292 copyEntryOperands.append(dataClauseOperands.begin() + crtDataStart,
2293 dataClauseOperands.end());
2294 } else if (const auto *copyinClause =
2295 std::get_if<Fortran::parser::AccClause::Copyin>(&clause.u)) {
2296 genDataOperandOperationsWithModifier<mlir::acc::CopyinOp,
2297 Fortran::parser::AccClause::Copyin>(
2298 copyinClause, converter, semanticsContext, stmtCtx,
2299 Fortran::parser::AccDataModifier::Modifier::ReadOnly,
2300 dataClauseOperands, mlir::acc::DataClause::acc_copyin,
2301 mlir::acc::DataClause::acc_copyin_readonly, async, asyncDeviceTypes,
2302 asyncOnlyDeviceTypes);
2303 } else if (const auto *copyoutClause =
2304 std::get_if<Fortran::parser::AccClause::Copyout>(
2305 &clause.u)) {
2306 auto crtDataStart = dataClauseOperands.size();
2307 genDataOperandOperationsWithModifier<mlir::acc::CreateOp,
2308 Fortran::parser::AccClause::Copyout>(
2309 copyoutClause, converter, semanticsContext, stmtCtx,
2310 Fortran::parser::AccDataModifier::Modifier::ReadOnly,
2311 dataClauseOperands, mlir::acc::DataClause::acc_copyout,
2312 mlir::acc::DataClause::acc_copyout_zero, async, asyncDeviceTypes,
2313 asyncOnlyDeviceTypes);
2314 copyoutEntryOperands.append(dataClauseOperands.begin() + crtDataStart,
2315 dataClauseOperands.end());
2316 } else if (const auto *createClause =
2317 std::get_if<Fortran::parser::AccClause::Create>(&clause.u)) {
2318 auto crtDataStart = dataClauseOperands.size();
2319 genDataOperandOperationsWithModifier<mlir::acc::CreateOp,
2320 Fortran::parser::AccClause::Create>(
2321 createClause, converter, semanticsContext, stmtCtx,
2322 Fortran::parser::AccDataModifier::Modifier::Zero, dataClauseOperands,
2323 mlir::acc::DataClause::acc_create,
2324 mlir::acc::DataClause::acc_create_zero, async, asyncDeviceTypes,
2325 asyncOnlyDeviceTypes);
2326 createEntryOperands.append(dataClauseOperands.begin() + crtDataStart,
2327 dataClauseOperands.end());
2328 } else if (const auto *noCreateClause =
2329 std::get_if<Fortran::parser::AccClause::NoCreate>(
2330 &clause.u)) {
2331 genDataOperandOperations<mlir::acc::NoCreateOp>(
2332 noCreateClause->v, converter, semanticsContext, stmtCtx,
2333 dataClauseOperands, mlir::acc::DataClause::acc_no_create,
2334 /*structured=*/true, /*implicit=*/false, async, asyncDeviceTypes,
2335 asyncOnlyDeviceTypes);
2336 } else if (const auto *presentClause =
2337 std::get_if<Fortran::parser::AccClause::Present>(
2338 &clause.u)) {
2339 genDataOperandOperations<mlir::acc::PresentOp>(
2340 presentClause->v, converter, semanticsContext, stmtCtx,
2341 dataClauseOperands, mlir::acc::DataClause::acc_present,
2342 /*structured=*/true, /*implicit=*/false, async, asyncDeviceTypes,
2343 asyncOnlyDeviceTypes);
2344 } else if (const auto *devicePtrClause =
2345 std::get_if<Fortran::parser::AccClause::Deviceptr>(
2346 &clause.u)) {
2347 genDataOperandOperations<mlir::acc::DevicePtrOp>(
2348 devicePtrClause->v, converter, semanticsContext, stmtCtx,
2349 dataClauseOperands, mlir::acc::DataClause::acc_deviceptr,
2350 /*structured=*/true, /*implicit=*/false, async, asyncDeviceTypes,
2351 asyncOnlyDeviceTypes);
2352 } else if (const auto *attachClause =
2353 std::get_if<Fortran::parser::AccClause::Attach>(&clause.u)) {
2354 auto crtDataStart = dataClauseOperands.size();
2355 genDataOperandOperations<mlir::acc::AttachOp>(
2356 attachClause->v, converter, semanticsContext, stmtCtx,
2357 dataClauseOperands, mlir::acc::DataClause::acc_attach,
2358 /*structured=*/true, /*implicit=*/false, async, asyncDeviceTypes,
2359 asyncOnlyDeviceTypes);
2360 attachEntryOperands.append(dataClauseOperands.begin() + crtDataStart,
2361 dataClauseOperands.end());
2362 } else if (const auto *privateClause =
2363 std::get_if<Fortran::parser::AccClause::Private>(
2364 &clause.u)) {
2365 if (!combinedConstructs)
2366 genPrivatizations<mlir::acc::PrivateRecipeOp>(
2367 privateClause->v, converter, semanticsContext, stmtCtx,
2368 privateOperands, privatizations, async, asyncDeviceTypes,
2369 asyncOnlyDeviceTypes);
2370 } else if (const auto *firstprivateClause =
2371 std::get_if<Fortran::parser::AccClause::Firstprivate>(
2372 &clause.u)) {
2373 genPrivatizations<mlir::acc::FirstprivateRecipeOp>(
2374 firstprivateClause->v, converter, semanticsContext, stmtCtx,
2375 firstprivateOperands, firstPrivatizations, async, asyncDeviceTypes,
2376 asyncOnlyDeviceTypes);
2377 } else if (const auto *reductionClause =
2378 std::get_if<Fortran::parser::AccClause::Reduction>(
2379 &clause.u)) {
2380 // A reduction clause on a combined construct is treated as if it appeared
2381 // on the loop construct. So don't generate a reduction clause when it is
2382 // combined - delay it to the loop. However, a reduction clause on a
2383 // combined construct implies a copy clause so issue an implicit copy
2384 // instead.
2385 if (!combinedConstructs) {
2386 genReductions(reductionClause->v, converter, semanticsContext, stmtCtx,
2387 reductionOperands, reductionRecipes, async,
2388 asyncDeviceTypes, asyncOnlyDeviceTypes);
2389 } else {
2390 auto crtDataStart = dataClauseOperands.size();
2391 genDataOperandOperations<mlir::acc::CopyinOp>(
2392 std::get<Fortran::parser::AccObjectList>(reductionClause->v.t),
2393 converter, semanticsContext, stmtCtx, dataClauseOperands,
2394 mlir::acc::DataClause::acc_reduction,
2395 /*structured=*/true, /*implicit=*/true, async, asyncDeviceTypes,
2396 asyncOnlyDeviceTypes);
2397 copyEntryOperands.append(dataClauseOperands.begin() + crtDataStart,
2398 dataClauseOperands.end());
2399 }
2400 } else if (const auto *defaultClause =
2401 std::get_if<Fortran::parser::AccClause::Default>(
2402 &clause.u)) {
2403 if ((defaultClause->v).v == llvm::acc::DefaultValue::ACC_Default_none)
2404 hasDefaultNone = true;
2405 else if ((defaultClause->v).v ==
2406 llvm::acc::DefaultValue::ACC_Default_present)
2407 hasDefaultPresent = true;
2408 }
2409 }
2410
2411 // Prepare the operand segment size attribute and the operands value range.
2412 llvm::SmallVector<mlir::Value, 8> operands;
2413 llvm::SmallVector<int32_t, 8> operandSegments;
2414 addOperands(operands, operandSegments, async);
2415 addOperands(operands, operandSegments, waitOperands);
2416 if constexpr (!std::is_same_v<Op, mlir::acc::SerialOp>) {
2417 addOperands(operands, operandSegments, numGangs);
2418 addOperands(operands, operandSegments, numWorkers);
2419 addOperands(operands, operandSegments, vectorLength);
2420 }
2421 addOperand(operands, operandSegments, ifCond);
2422 addOperand(operands, operandSegments, selfCond);
2423 if constexpr (!std::is_same_v<Op, mlir::acc::KernelsOp>) {
2424 addOperands(operands, operandSegments, reductionOperands);
2425 addOperands(operands, operandSegments, privateOperands);
2426 addOperands(operands, operandSegments, firstprivateOperands);
2427 }
2428 addOperands(operands, operandSegments, dataClauseOperands);
2429
2430 Op computeOp;
2431 if constexpr (std::is_same_v<Op, mlir::acc::KernelsOp>)
2432 computeOp = createRegionOp<Op, mlir::acc::TerminatorOp>(
2433 builder, currentLocation, currentLocation, eval, operands,
2434 operandSegments, /*outerCombined=*/combinedConstructs.has_value());
2435 else
2436 computeOp = createRegionOp<Op, mlir::acc::YieldOp>(
2437 builder, currentLocation, currentLocation, eval, operands,
2438 operandSegments, /*outerCombined=*/combinedConstructs.has_value());
2439
2440 if (addSelfAttr)
2441 computeOp.setSelfAttrAttr(builder.getUnitAttr());
2442
2443 if (hasDefaultNone)
2444 computeOp.setDefaultAttr(mlir::acc::ClauseDefaultValue::None);
2445 if (hasDefaultPresent)
2446 computeOp.setDefaultAttr(mlir::acc::ClauseDefaultValue::Present);
2447
2448 if constexpr (!std::is_same_v<Op, mlir::acc::SerialOp>) {
2449 if (!numWorkersDeviceTypes.empty())
2450 computeOp.setNumWorkersDeviceTypeAttr(
2451 mlir::ArrayAttr::get(builder.getContext(), numWorkersDeviceTypes));
2452 if (!vectorLengthDeviceTypes.empty())
2453 computeOp.setVectorLengthDeviceTypeAttr(
2454 mlir::ArrayAttr::get(builder.getContext(), vectorLengthDeviceTypes));
2455 if (!numGangsDeviceTypes.empty())
2456 computeOp.setNumGangsDeviceTypeAttr(
2457 mlir::ArrayAttr::get(builder.getContext(), numGangsDeviceTypes));
2458 if (!numGangsSegments.empty())
2459 computeOp.setNumGangsSegmentsAttr(
2460 builder.getDenseI32ArrayAttr(numGangsSegments));
2461 }
2462 if (!asyncDeviceTypes.empty())
2463 computeOp.setAsyncOperandsDeviceTypeAttr(
2464 builder.getArrayAttr(asyncDeviceTypes));
2465 if (!asyncOnlyDeviceTypes.empty())
2466 computeOp.setAsyncOnlyAttr(builder.getArrayAttr(asyncOnlyDeviceTypes));
2467
2468 if (!waitOperandsDeviceTypes.empty())
2469 computeOp.setWaitOperandsDeviceTypeAttr(
2470 builder.getArrayAttr(waitOperandsDeviceTypes));
2471 if (!waitOperandsSegments.empty())
2472 computeOp.setWaitOperandsSegmentsAttr(
2473 builder.getDenseI32ArrayAttr(waitOperandsSegments));
2474 if (!hasWaitDevnums.empty())
2475 computeOp.setHasWaitDevnumAttr(builder.getBoolArrayAttr(hasWaitDevnums));
2476 if (!waitOnlyDeviceTypes.empty())
2477 computeOp.setWaitOnlyAttr(builder.getArrayAttr(waitOnlyDeviceTypes));
2478
2479 if constexpr (!std::is_same_v<Op, mlir::acc::KernelsOp>) {
2480 if (!privatizations.empty())
2481 computeOp.setPrivatizationsAttr(
2482 mlir::ArrayAttr::get(builder.getContext(), privatizations));
2483 if (!reductionRecipes.empty())
2484 computeOp.setReductionRecipesAttr(
2485 mlir::ArrayAttr::get(builder.getContext(), reductionRecipes));
2486 if (!firstPrivatizations.empty())
2487 computeOp.setFirstprivatizationsAttr(
2488 mlir::ArrayAttr::get(builder.getContext(), firstPrivatizations));
2489 }
2490
2491 if (combinedConstructs)
2492 computeOp.setCombinedAttr(builder.getUnitAttr());
2493
2494 auto insPt = builder.saveInsertionPoint();
2495 builder.setInsertionPointAfter(computeOp);
2496
2497 // Create the exit operations after the region.
2498 genDataExitOperations<mlir::acc::CopyinOp, mlir::acc::CopyoutOp>(
2499 builder, copyEntryOperands, /*structured=*/true);
2500 genDataExitOperations<mlir::acc::CreateOp, mlir::acc::CopyoutOp>(
2501 builder, copyoutEntryOperands, /*structured=*/true);
2502 genDataExitOperations<mlir::acc::AttachOp, mlir::acc::DetachOp>(
2503 builder, attachEntryOperands, /*structured=*/true);
2504 genDataExitOperations<mlir::acc::CreateOp, mlir::acc::DeleteOp>(
2505 builder, createEntryOperands, /*structured=*/true);
2506
2507 builder.restoreInsertionPoint(insPt);
2508 return computeOp;
2509 }
2510
2511 static void genACCDataOp(Fortran::lower::AbstractConverter &converter,
2512 mlir::Location currentLocation,
2513 Fortran::lower::pft::Evaluation &eval,
2514 Fortran::semantics::SemanticsContext &semanticsContext,
2515 Fortran::lower::StatementContext &stmtCtx,
2516 const Fortran::parser::AccClauseList &accClauseList) {
2517 mlir::Value ifCond;
2518 llvm::SmallVector<mlir::Value> attachEntryOperands, createEntryOperands,
2519 copyEntryOperands, copyoutEntryOperands, dataClauseOperands, waitOperands,
2520 async;
2521 llvm::SmallVector<mlir::Attribute> asyncDeviceTypes, asyncOnlyDeviceTypes,
2522 waitOperandsDeviceTypes, waitOnlyDeviceTypes;
2523 llvm::SmallVector<int32_t> waitOperandsSegments;
2524 llvm::SmallVector<bool> hasWaitDevnums;
2525
2526 bool hasDefaultNone = false;
2527 bool hasDefaultPresent = false;
2528
2529 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
2530
2531 // device_type attribute is set to `none` until a device_type clause is
2532 // encountered.
2533 llvm::SmallVector<mlir::Attribute> crtDeviceTypes;
2534 crtDeviceTypes.push_back(mlir::acc::DeviceTypeAttr::get(
2535 builder.getContext(), mlir::acc::DeviceType::None));
2536
2537 // Lower clauses values mapped to operands and array attributes.
2538 // Keep track of each group of operands separately as clauses can appear
2539 // more than once.
2540
2541 // Process the clauses that may have a specified device_type first.
2542 for (const Fortran::parser::AccClause &clause : accClauseList.v) {
2543 if (const auto *asyncClause =
2544 std::get_if<Fortran::parser::AccClause::Async>(&clause.u)) {
2545 genAsyncClause(converter, asyncClause, async, asyncDeviceTypes,
2546 asyncOnlyDeviceTypes, crtDeviceTypes, stmtCtx);
2547 } else if (const auto *waitClause =
2548 std::get_if<Fortran::parser::AccClause::Wait>(&clause.u)) {
2549 genWaitClauseWithDeviceType(converter, waitClause, waitOperands,
2550 waitOperandsDeviceTypes, waitOnlyDeviceTypes,
2551 hasWaitDevnums, waitOperandsSegments,
2552 crtDeviceTypes, stmtCtx);
2553 } else if (const auto *deviceTypeClause =
2554 std::get_if<Fortran::parser::AccClause::DeviceType>(
2555 &clause.u)) {
2556 crtDeviceTypes.clear();
2557 gatherDeviceTypeAttrs(builder, deviceTypeClause, crtDeviceTypes);
2558 }
2559 }
2560
2561 // Process the clauses independent of device_type.
2562 for (const Fortran::parser::AccClause &clause : accClauseList.v) {
2563 mlir::Location clauseLocation = converter.genLocation(clause.source);
2564 if (const auto *ifClause =
2565 std::get_if<Fortran::parser::AccClause::If>(&clause.u)) {
2566 genIfClause(converter, clauseLocation, ifClause, ifCond, stmtCtx);
2567 } else if (const auto *copyClause =
2568 std::get_if<Fortran::parser::AccClause::Copy>(&clause.u)) {
2569 auto crtDataStart = dataClauseOperands.size();
2570 genDataOperandOperations<mlir::acc::CopyinOp>(
2571 copyClause->v, converter, semanticsContext, stmtCtx,
2572 dataClauseOperands, mlir::acc::DataClause::acc_copy,
2573 /*structured=*/true, /*implicit=*/false, async, asyncDeviceTypes,
2574 asyncOnlyDeviceTypes);
2575 copyEntryOperands.append(dataClauseOperands.begin() + crtDataStart,
2576 dataClauseOperands.end());
2577 } else if (const auto *copyinClause =
2578 std::get_if<Fortran::parser::AccClause::Copyin>(&clause.u)) {
2579 genDataOperandOperationsWithModifier<mlir::acc::CopyinOp,
2580 Fortran::parser::AccClause::Copyin>(
2581 copyinClause, converter, semanticsContext, stmtCtx,
2582 Fortran::parser::AccDataModifier::Modifier::ReadOnly,
2583 dataClauseOperands, mlir::acc::DataClause::acc_copyin,
2584 mlir::acc::DataClause::acc_copyin_readonly, async, asyncDeviceTypes,
2585 asyncOnlyDeviceTypes);
2586 } else if (const auto *copyoutClause =
2587 std::get_if<Fortran::parser::AccClause::Copyout>(
2588 &clause.u)) {
2589 auto crtDataStart = dataClauseOperands.size();
2590 genDataOperandOperationsWithModifier<mlir::acc::CreateOp,
2591 Fortran::parser::AccClause::Copyout>(
2592 copyoutClause, converter, semanticsContext, stmtCtx,
2593 Fortran::parser::AccDataModifier::Modifier::Zero, dataClauseOperands,
2594 mlir::acc::DataClause::acc_copyout,
2595 mlir::acc::DataClause::acc_copyout_zero, async, asyncDeviceTypes,
2596 asyncOnlyDeviceTypes);
2597 copyoutEntryOperands.append(dataClauseOperands.begin() + crtDataStart,
2598 dataClauseOperands.end());
2599 } else if (const auto *createClause =
2600 std::get_if<Fortran::parser::AccClause::Create>(&clause.u)) {
2601 auto crtDataStart = dataClauseOperands.size();
2602 genDataOperandOperationsWithModifier<mlir::acc::CreateOp,
2603 Fortran::parser::AccClause::Create>(
2604 createClause, converter, semanticsContext, stmtCtx,
2605 Fortran::parser::AccDataModifier::Modifier::Zero, dataClauseOperands,
2606 mlir::acc::DataClause::acc_create,
2607 mlir::acc::DataClause::acc_create_zero, async, asyncDeviceTypes,
2608 asyncOnlyDeviceTypes);
2609 createEntryOperands.append(dataClauseOperands.begin() + crtDataStart,
2610 dataClauseOperands.end());
2611 } else if (const auto *noCreateClause =
2612 std::get_if<Fortran::parser::AccClause::NoCreate>(
2613 &clause.u)) {
2614 genDataOperandOperations<mlir::acc::NoCreateOp>(
2615 noCreateClause->v, converter, semanticsContext, stmtCtx,
2616 dataClauseOperands, mlir::acc::DataClause::acc_no_create,
2617 /*structured=*/true, /*implicit=*/false, async, asyncDeviceTypes,
2618 asyncOnlyDeviceTypes);
2619 } else if (const auto *presentClause =
2620 std::get_if<Fortran::parser::AccClause::Present>(
2621 &clause.u)) {
2622 genDataOperandOperations<mlir::acc::PresentOp>(
2623 presentClause->v, converter, semanticsContext, stmtCtx,
2624 dataClauseOperands, mlir::acc::DataClause::acc_present,
2625 /*structured=*/true, /*implicit=*/false, async, asyncDeviceTypes,
2626 asyncOnlyDeviceTypes);
2627 } else if (const auto *deviceptrClause =
2628 std::get_if<Fortran::parser::AccClause::Deviceptr>(
2629 &clause.u)) {
2630 genDataOperandOperations<mlir::acc::DevicePtrOp>(
2631 deviceptrClause->v, converter, semanticsContext, stmtCtx,
2632 dataClauseOperands, mlir::acc::DataClause::acc_deviceptr,
2633 /*structured=*/true, /*implicit=*/false, async, asyncDeviceTypes,
2634 asyncOnlyDeviceTypes);
2635 } else if (const auto *attachClause =
2636 std::get_if<Fortran::parser::AccClause::Attach>(&clause.u)) {
2637 auto crtDataStart = dataClauseOperands.size();
2638 genDataOperandOperations<mlir::acc::AttachOp>(
2639 attachClause->v, converter, semanticsContext, stmtCtx,
2640 dataClauseOperands, mlir::acc::DataClause::acc_attach,
2641 /*structured=*/true, /*implicit=*/false, async, asyncDeviceTypes,
2642 asyncOnlyDeviceTypes);
2643 attachEntryOperands.append(dataClauseOperands.begin() + crtDataStart,
2644 dataClauseOperands.end());
2645 } else if(const auto *defaultClause =
2646 std::get_if<Fortran::parser::AccClause::Default>(&clause.u)) {
2647 if ((defaultClause->v).v == llvm::acc::DefaultValue::ACC_Default_none)
2648 hasDefaultNone = true;
2649 else if ((defaultClause->v).v == llvm::acc::DefaultValue::ACC_Default_present)
2650 hasDefaultPresent = true;
2651 }
2652 }
2653
2654 // Prepare the operand segment size attribute and the operands value range.
2655 llvm::SmallVector<mlir::Value> operands;
2656 llvm::SmallVector<int32_t> operandSegments;
2657 addOperand(operands, operandSegments, ifCond);
2658 addOperands(operands, operandSegments, async);
2659 addOperands(operands, operandSegments, waitOperands);
2660 addOperands(operands, operandSegments, dataClauseOperands);
2661
2662 if (dataClauseOperands.empty() && !hasDefaultNone && !hasDefaultPresent)
2663 return;
2664
2665 auto dataOp = createRegionOp<mlir::acc::DataOp, mlir::acc::TerminatorOp>(
2666 builder, currentLocation, currentLocation, eval, operands,
2667 operandSegments);
2668
2669 if (!asyncDeviceTypes.empty())
2670 dataOp.setAsyncOperandsDeviceTypeAttr(
2671 builder.getArrayAttr(asyncDeviceTypes));
2672 if (!asyncOnlyDeviceTypes.empty())
2673 dataOp.setAsyncOnlyAttr(builder.getArrayAttr(asyncOnlyDeviceTypes));
2674 if (!waitOperandsDeviceTypes.empty())
2675 dataOp.setWaitOperandsDeviceTypeAttr(
2676 builder.getArrayAttr(waitOperandsDeviceTypes));
2677 if (!waitOperandsSegments.empty())
2678 dataOp.setWaitOperandsSegmentsAttr(
2679 builder.getDenseI32ArrayAttr(waitOperandsSegments));
2680 if (!hasWaitDevnums.empty())
2681 dataOp.setHasWaitDevnumAttr(builder.getBoolArrayAttr(hasWaitDevnums));
2682 if (!waitOnlyDeviceTypes.empty())
2683 dataOp.setWaitOnlyAttr(builder.getArrayAttr(waitOnlyDeviceTypes));
2684
2685 if (hasDefaultNone)
2686 dataOp.setDefaultAttr(mlir::acc::ClauseDefaultValue::None);
2687 if (hasDefaultPresent)
2688 dataOp.setDefaultAttr(mlir::acc::ClauseDefaultValue::Present);
2689
2690 auto insPt = builder.saveInsertionPoint();
2691 builder.setInsertionPointAfter(dataOp);
2692
2693 // Create the exit operations after the region.
2694 genDataExitOperations<mlir::acc::CopyinOp, mlir::acc::CopyoutOp>(
2695 builder, copyEntryOperands, /*structured=*/true);
2696 genDataExitOperations<mlir::acc::CreateOp, mlir::acc::CopyoutOp>(
2697 builder, copyoutEntryOperands, /*structured=*/true);
2698 genDataExitOperations<mlir::acc::AttachOp, mlir::acc::DetachOp>(
2699 builder, attachEntryOperands, /*structured=*/true);
2700 genDataExitOperations<mlir::acc::CreateOp, mlir::acc::DeleteOp>(
2701 builder, createEntryOperands, /*structured=*/true);
2702
2703 builder.restoreInsertionPoint(insPt);
2704 }
2705
2706 static void
2707 genACCHostDataOp(Fortran::lower::AbstractConverter &converter,
2708 mlir::Location currentLocation,
2709 Fortran::lower::pft::Evaluation &eval,
2710 Fortran::semantics::SemanticsContext &semanticsContext,
2711 Fortran::lower::StatementContext &stmtCtx,
2712 const Fortran::parser::AccClauseList &accClauseList) {
2713 mlir::Value ifCond;
2714 llvm::SmallVector<mlir::Value> dataOperands;
2715 bool addIfPresentAttr = false;
2716
2717 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
2718
2719 for (const Fortran::parser::AccClause &clause : accClauseList.v) {
2720 mlir::Location clauseLocation = converter.genLocation(clause.source);
2721 if (const auto *ifClause =
2722 std::get_if<Fortran::parser::AccClause::If>(&clause.u)) {
2723 genIfClause(converter, clauseLocation, ifClause, ifCond, stmtCtx);
2724 } else if (const auto *useDevice =
2725 std::get_if<Fortran::parser::AccClause::UseDevice>(
2726 &clause.u)) {
2727 genDataOperandOperations<mlir::acc::UseDeviceOp>(
2728 useDevice->v, converter, semanticsContext, stmtCtx, dataOperands,
2729 mlir::acc::DataClause::acc_use_device,
2730 /*structured=*/true, /*implicit=*/false, /*async=*/{},
2731 /*asyncDeviceTypes=*/{}, /*asyncOnlyDeviceTypes=*/{});
2732 } else if (std::get_if<Fortran::parser::AccClause::IfPresent>(&clause.u)) {
2733 addIfPresentAttr = true;
2734 }
2735 }
2736
2737 if (ifCond) {
2738 if (auto cst =
2739 mlir::dyn_cast<mlir::arith::ConstantOp>(ifCond.getDefiningOp()))
2740 if (auto boolAttr = mlir::dyn_cast<mlir::BoolAttr>(cst.getValue())) {
2741 if (boolAttr.getValue()) {
2742 // get rid of the if condition if it is always true.
2743 ifCond = mlir::Value();
2744 } else {
2745 // Do not generate the acc.host_data op if the if condition is always
2746 // false.
2747 return;
2748 }
2749 }
2750 }
2751
2752 // Prepare the operand segment size attribute and the operands value range.
2753 llvm::SmallVector<mlir::Value> operands;
2754 llvm::SmallVector<int32_t> operandSegments;
2755 addOperand(operands, operandSegments, ifCond);
2756 addOperands(operands, operandSegments, dataOperands);
2757
2758 auto hostDataOp =
2759 createRegionOp<mlir::acc::HostDataOp, mlir::acc::TerminatorOp>(
2760 builder, currentLocation, currentLocation, eval, operands,
2761 operandSegments);
2762
2763 if (addIfPresentAttr)
2764 hostDataOp.setIfPresentAttr(builder.getUnitAttr());
2765 }
2766
2767 static void
2768 genACC(Fortran::lower::AbstractConverter &converter,
2769 Fortran::semantics::SemanticsContext &semanticsContext,
2770 Fortran::lower::pft::Evaluation &eval,
2771 const Fortran::parser::OpenACCBlockConstruct &blockConstruct) {
2772 const auto &beginBlockDirective =
2773 std::get<Fortran::parser::AccBeginBlockDirective>(blockConstruct.t);
2774 const auto &blockDirective =
2775 std::get<Fortran::parser::AccBlockDirective>(beginBlockDirective.t);
2776 const auto &accClauseList =
2777 std::get<Fortran::parser::AccClauseList>(beginBlockDirective.t);
2778
2779 mlir::Location currentLocation = converter.genLocation(blockDirective.source);
2780 Fortran::lower::StatementContext stmtCtx;
2781
2782 if (blockDirective.v == llvm::acc::ACCD_parallel) {
2783 createComputeOp<mlir::acc::ParallelOp>(converter, currentLocation, eval,
2784 semanticsContext, stmtCtx,
2785 accClauseList);
2786 } else if (blockDirective.v == llvm::acc::ACCD_data) {
2787 genACCDataOp(converter, currentLocation, eval, semanticsContext, stmtCtx,
2788 accClauseList);
2789 } else if (blockDirective.v == llvm::acc::ACCD_serial) {
2790 createComputeOp<mlir::acc::SerialOp>(converter, currentLocation, eval,
2791 semanticsContext, stmtCtx,
2792 accClauseList);
2793 } else if (blockDirective.v == llvm::acc::ACCD_kernels) {
2794 createComputeOp<mlir::acc::KernelsOp>(converter, currentLocation, eval,
2795 semanticsContext, stmtCtx,
2796 accClauseList);
2797 } else if (blockDirective.v == llvm::acc::ACCD_host_data) {
2798 genACCHostDataOp(converter, currentLocation, eval, semanticsContext,
2799 stmtCtx, accClauseList);
2800 }
2801 }
2802
2803 static void
2804 genACC(Fortran::lower::AbstractConverter &converter,
2805 Fortran::semantics::SemanticsContext &semanticsContext,
2806 Fortran::lower::pft::Evaluation &eval,
2807 const Fortran::parser::OpenACCCombinedConstruct &combinedConstruct) {
2808 const auto &beginCombinedDirective =
2809 std::get<Fortran::parser::AccBeginCombinedDirective>(combinedConstruct.t);
2810 const auto &combinedDirective =
2811 std::get<Fortran::parser::AccCombinedDirective>(beginCombinedDirective.t);
2812 const auto &accClauseList =
2813 std::get<Fortran::parser::AccClauseList>(beginCombinedDirective.t);
2814 const auto &outerDoConstruct =
2815 std::get<std::optional<Fortran::parser::DoConstruct>>(
2816 combinedConstruct.t);
2817
2818 mlir::Location currentLocation =
2819 converter.genLocation(beginCombinedDirective.source);
2820 Fortran::lower::StatementContext stmtCtx;
2821
2822 if (combinedDirective.v == llvm::acc::ACCD_kernels_loop) {
2823 createComputeOp<mlir::acc::KernelsOp>(
2824 converter, currentLocation, eval, semanticsContext, stmtCtx,
2825 accClauseList, mlir::acc::CombinedConstructsType::KernelsLoop);
2826 createLoopOp(converter, currentLocation, semanticsContext, stmtCtx,
2827 *outerDoConstruct, eval, accClauseList,
2828 mlir::acc::CombinedConstructsType::KernelsLoop);
2829 } else if (combinedDirective.v == llvm::acc::ACCD_parallel_loop) {
2830 createComputeOp<mlir::acc::ParallelOp>(
2831 converter, currentLocation, eval, semanticsContext, stmtCtx,
2832 accClauseList, mlir::acc::CombinedConstructsType::ParallelLoop);
2833 createLoopOp(converter, currentLocation, semanticsContext, stmtCtx,
2834 *outerDoConstruct, eval, accClauseList,
2835 mlir::acc::CombinedConstructsType::ParallelLoop);
2836 } else if (combinedDirective.v == llvm::acc::ACCD_serial_loop) {
2837 createComputeOp<mlir::acc::SerialOp>(
2838 converter, currentLocation, eval, semanticsContext, stmtCtx,
2839 accClauseList, mlir::acc::CombinedConstructsType::SerialLoop);
2840 createLoopOp(converter, currentLocation, semanticsContext, stmtCtx,
2841 *outerDoConstruct, eval, accClauseList,
2842 mlir::acc::CombinedConstructsType::SerialLoop);
2843 } else {
2844 llvm::report_fatal_error("Unknown combined construct encountered");
2845 }
2846 }
2847
2848 static void
2849 genACCEnterDataOp(Fortran::lower::AbstractConverter &converter,
2850 mlir::Location currentLocation,
2851 Fortran::semantics::SemanticsContext &semanticsContext,
2852 Fortran::lower::StatementContext &stmtCtx,
2853 const Fortran::parser::AccClauseList &accClauseList) {
2854 mlir::Value ifCond, async, waitDevnum;
2855 llvm::SmallVector<mlir::Value> waitOperands, dataClauseOperands;
2856
2857 // Async, wait and self clause have optional values but can be present with
2858 // no value as well. When there is no value, the op has an attribute to
2859 // represent the clause.
2860 bool addAsyncAttr = false;
2861 bool addWaitAttr = false;
2862
2863 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
2864
2865 // Lower clauses values mapped to operands.
2866 // Keep track of each group of operands separately as clauses can appear
2867 // more than once.
2868
2869 // Process the async clause first.
2870 for (const Fortran::parser::AccClause &clause : accClauseList.v) {
2871 if (const auto *asyncClause =
2872 std::get_if<Fortran::parser::AccClause::Async>(&clause.u)) {
2873 genAsyncClause(converter, asyncClause, async, addAsyncAttr, stmtCtx);
2874 }
2875 }
2876
2877 // The async clause of 'enter data' applies to all device types,
2878 // so propagate the async clause to copyin/create/attach ops
2879 // as if it is an async clause without preceding device_type clause.
2880 llvm::SmallVector<mlir::Attribute> asyncDeviceTypes, asyncOnlyDeviceTypes;
2881 llvm::SmallVector<mlir::Value> asyncValues;
2882 auto noneDeviceTypeAttr = mlir::acc::DeviceTypeAttr::get(
2883 firOpBuilder.getContext(), mlir::acc::DeviceType::None);
2884 if (addAsyncAttr) {
2885 asyncOnlyDeviceTypes.push_back(noneDeviceTypeAttr);
2886 } else if (async) {
2887 asyncValues.push_back(async);
2888 asyncDeviceTypes.push_back(noneDeviceTypeAttr);
2889 }
2890
2891 for (const Fortran::parser::AccClause &clause : accClauseList.v) {
2892 mlir::Location clauseLocation = converter.genLocation(clause.source);
2893 if (const auto *ifClause =
2894 std::get_if<Fortran::parser::AccClause::If>(&clause.u)) {
2895 genIfClause(converter, clauseLocation, ifClause, ifCond, stmtCtx);
2896 } else if (const auto *waitClause =
2897 std::get_if<Fortran::parser::AccClause::Wait>(&clause.u)) {
2898 genWaitClause(converter, waitClause, waitOperands, waitDevnum,
2899 addWaitAttr, stmtCtx);
2900 } else if (const auto *copyinClause =
2901 std::get_if<Fortran::parser::AccClause::Copyin>(&clause.u)) {
2902 const Fortran::parser::AccObjectListWithModifier &listWithModifier =
2903 copyinClause->v;
2904 const auto &accObjectList =
2905 std::get<Fortran::parser::AccObjectList>(listWithModifier.t);
2906 genDataOperandOperations<mlir::acc::CopyinOp>(
2907 accObjectList, converter, semanticsContext, stmtCtx,
2908 dataClauseOperands, mlir::acc::DataClause::acc_copyin, false,
2909 /*implicit=*/false, asyncValues, asyncDeviceTypes,
2910 asyncOnlyDeviceTypes);
2911 } else if (const auto *createClause =
2912 std::get_if<Fortran::parser::AccClause::Create>(&clause.u)) {
2913 const Fortran::parser::AccObjectListWithModifier &listWithModifier =
2914 createClause->v;
2915 const auto &accObjectList =
2916 std::get<Fortran::parser::AccObjectList>(listWithModifier.t);
2917 const auto &modifier =
2918 std::get<std::optional<Fortran::parser::AccDataModifier>>(
2919 listWithModifier.t);
2920 mlir::acc::DataClause clause = mlir::acc::DataClause::acc_create;
2921 if (modifier &&
2922 (*modifier).v == Fortran::parser::AccDataModifier::Modifier::Zero)
2923 clause = mlir::acc::DataClause::acc_create_zero;
2924 genDataOperandOperations<mlir::acc::CreateOp>(
2925 accObjectList, converter, semanticsContext, stmtCtx,
2926 dataClauseOperands, clause, false, /*implicit=*/false, asyncValues,
2927 asyncDeviceTypes, asyncOnlyDeviceTypes);
2928 } else if (const auto *attachClause =
2929 std::get_if<Fortran::parser::AccClause::Attach>(&clause.u)) {
2930 genDataOperandOperations<mlir::acc::AttachOp>(
2931 attachClause->v, converter, semanticsContext, stmtCtx,
2932 dataClauseOperands, mlir::acc::DataClause::acc_attach, false,
2933 /*implicit=*/false, asyncValues, asyncDeviceTypes,
2934 asyncOnlyDeviceTypes);
2935 } else if (!std::get_if<Fortran::parser::AccClause::Async>(&clause.u)) {
2936 llvm::report_fatal_error(
2937 "Unknown clause in ENTER DATA directive lowering");
2938 }
2939 }
2940
2941 // Prepare the operand segment size attribute and the operands value range.
2942 llvm::SmallVector<mlir::Value, 16> operands;
2943 llvm::SmallVector<int32_t, 8> operandSegments;
2944 addOperand(operands, operandSegments, ifCond);
2945 addOperand(operands, operandSegments, async);
2946 addOperand(operands, operandSegments, waitDevnum);
2947 addOperands(operands, operandSegments, waitOperands);
2948 addOperands(operands, operandSegments, dataClauseOperands);
2949
2950 mlir::acc::EnterDataOp enterDataOp = createSimpleOp<mlir::acc::EnterDataOp>(
2951 firOpBuilder, currentLocation, operands, operandSegments);
2952
2953 if (addAsyncAttr)
2954 enterDataOp.setAsyncAttr(firOpBuilder.getUnitAttr());
2955 if (addWaitAttr)
2956 enterDataOp.setWaitAttr(firOpBuilder.getUnitAttr());
2957 }
2958
2959 static void
2960 genACCExitDataOp(Fortran::lower::AbstractConverter &converter,
2961 mlir::Location currentLocation,
2962 Fortran::semantics::SemanticsContext &semanticsContext,
2963 Fortran::lower::StatementContext &stmtCtx,
2964 const Fortran::parser::AccClauseList &accClauseList) {
2965 mlir::Value ifCond, async, waitDevnum;
2966 llvm::SmallVector<mlir::Value> waitOperands, dataClauseOperands,
2967 copyoutOperands, deleteOperands, detachOperands;
2968
2969 // Async and wait clause have optional values but can be present with
2970 // no value as well. When there is no value, the op has an attribute to
2971 // represent the clause.
2972 bool addAsyncAttr = false;
2973 bool addWaitAttr = false;
2974 bool addFinalizeAttr = false;
2975
2976 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
2977
2978 // Lower clauses values mapped to operands.
2979 // Keep track of each group of operands separately as clauses can appear
2980 // more than once.
2981
2982 // Process the async clause first.
2983 for (const Fortran::parser::AccClause &clause : accClauseList.v) {
2984 if (const auto *asyncClause =
2985 std::get_if<Fortran::parser::AccClause::Async>(&clause.u)) {
2986 genAsyncClause(converter, asyncClause, async, addAsyncAttr, stmtCtx);
2987 }
2988 }
2989
2990 // The async clause of 'exit data' applies to all device types,
2991 // so propagate the async clause to copyin/create/attach ops
2992 // as if it is an async clause without preceding device_type clause.
2993 llvm::SmallVector<mlir::Attribute> asyncDeviceTypes, asyncOnlyDeviceTypes;
2994 llvm::SmallVector<mlir::Value> asyncValues;
2995 auto noneDeviceTypeAttr = mlir::acc::DeviceTypeAttr::get(
2996 builder.getContext(), mlir::acc::DeviceType::None);
2997 if (addAsyncAttr) {
2998 asyncOnlyDeviceTypes.push_back(noneDeviceTypeAttr);
2999 } else if (async) {
3000 asyncValues.push_back(async);
3001 asyncDeviceTypes.push_back(noneDeviceTypeAttr);
3002 }
3003
3004 for (const Fortran::parser::AccClause &clause : accClauseList.v) {
3005 mlir::Location clauseLocation = converter.genLocation(clause.source);
3006 if (const auto *ifClause =
3007 std::get_if<Fortran::parser::AccClause::If>(&clause.u)) {
3008 genIfClause(converter, clauseLocation, ifClause, ifCond, stmtCtx);
3009 } else if (const auto *waitClause =
3010 std::get_if<Fortran::parser::AccClause::Wait>(&clause.u)) {
3011 genWaitClause(converter, waitClause, waitOperands, waitDevnum,
3012 addWaitAttr, stmtCtx);
3013 } else if (const auto *copyoutClause =
3014 std::get_if<Fortran::parser::AccClause::Copyout>(
3015 &clause.u)) {
3016 const Fortran::parser::AccObjectListWithModifier &listWithModifier =
3017 copyoutClause->v;
3018 const auto &accObjectList =
3019 std::get<Fortran::parser::AccObjectList>(listWithModifier.t);
3020 genDataOperandOperations<mlir::acc::GetDevicePtrOp>(
3021 accObjectList, converter, semanticsContext, stmtCtx, copyoutOperands,
3022 mlir::acc::DataClause::acc_copyout, false, /*implicit=*/false,
3023 asyncValues, asyncDeviceTypes, asyncOnlyDeviceTypes);
3024 } else if (const auto *deleteClause =
3025 std::get_if<Fortran::parser::AccClause::Delete>(&clause.u)) {
3026 genDataOperandOperations<mlir::acc::GetDevicePtrOp>(
3027 deleteClause->v, converter, semanticsContext, stmtCtx, deleteOperands,
3028 mlir::acc::DataClause::acc_delete, false, /*implicit=*/false,
3029 asyncValues, asyncDeviceTypes, asyncOnlyDeviceTypes);
3030 } else if (const auto *detachClause =
3031 std::get_if<Fortran::parser::AccClause::Detach>(&clause.u)) {
3032 genDataOperandOperations<mlir::acc::GetDevicePtrOp>(
3033 detachClause->v, converter, semanticsContext, stmtCtx, detachOperands,
3034 mlir::acc::DataClause::acc_detach, false, /*implicit=*/false,
3035 asyncValues, asyncDeviceTypes, asyncOnlyDeviceTypes);
3036 } else if (std::get_if<Fortran::parser::AccClause::Finalize>(&clause.u)) {
3037 addFinalizeAttr = true;
3038 }
3039 }
3040
3041 dataClauseOperands.append(copyoutOperands);
3042 dataClauseOperands.append(deleteOperands);
3043 dataClauseOperands.append(detachOperands);
3044
3045 // Prepare the operand segment size attribute and the operands value range.
3046 llvm::SmallVector<mlir::Value, 14> operands;
3047 llvm::SmallVector<int32_t, 7> operandSegments;
3048 addOperand(operands, operandSegments, ifCond);
3049 addOperand(operands, operandSegments, async);
3050 addOperand(operands, operandSegments, waitDevnum);
3051 addOperands(operands, operandSegments, waitOperands);
3052 addOperands(operands, operandSegments, dataClauseOperands);
3053
3054 mlir::acc::ExitDataOp exitDataOp = createSimpleOp<mlir::acc::ExitDataOp>(
3055 builder, currentLocation, operands, operandSegments);
3056
3057 if (addAsyncAttr)
3058 exitDataOp.setAsyncAttr(builder.getUnitAttr());
3059 if (addWaitAttr)
3060 exitDataOp.setWaitAttr(builder.getUnitAttr());
3061 if (addFinalizeAttr)
3062 exitDataOp.setFinalizeAttr(builder.getUnitAttr());
3063
3064 genDataExitOperations<mlir::acc::GetDevicePtrOp, mlir::acc::CopyoutOp>(
3065 builder, copyoutOperands, /*structured=*/false);
3066 genDataExitOperations<mlir::acc::GetDevicePtrOp, mlir::acc::DeleteOp>(
3067 builder, deleteOperands, /*structured=*/false);
3068 genDataExitOperations<mlir::acc::GetDevicePtrOp, mlir::acc::DetachOp>(
3069 builder, detachOperands, /*structured=*/false);
3070 }
3071
3072 template <typename Op>
3073 static void
3074 genACCInitShutdownOp(Fortran::lower::AbstractConverter &converter,
3075 mlir::Location currentLocation,
3076 const Fortran::parser::AccClauseList &accClauseList) {
3077 mlir::Value ifCond, deviceNum;
3078
3079 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
3080 Fortran::lower::StatementContext stmtCtx;
3081 llvm::SmallVector<mlir::Attribute> deviceTypes;
3082
3083 // Lower clauses values mapped to operands.
3084 // Keep track of each group of operands separately as clauses can appear
3085 // more than once.
3086 for (const Fortran::parser::AccClause &clause : accClauseList.v) {
3087 mlir::Location clauseLocation = converter.genLocation(clause.source);
3088 if (const auto *ifClause =
3089 std::get_if<Fortran::parser::AccClause::If>(&clause.u)) {
3090 genIfClause(converter, clauseLocation, ifClause, ifCond, stmtCtx);
3091 } else if (const auto *deviceNumClause =
3092 std::get_if<Fortran::parser::AccClause::DeviceNum>(
3093 &clause.u)) {
3094 deviceNum = fir::getBase(converter.genExprValue(
3095 *Fortran::semantics::GetExpr(deviceNumClause->v), stmtCtx));
3096 } else if (const auto *deviceTypeClause =
3097 std::get_if<Fortran::parser::AccClause::DeviceType>(
3098 &clause.u)) {
3099 gatherDeviceTypeAttrs(builder, deviceTypeClause, deviceTypes);
3100 }
3101 }
3102
3103 // Prepare the operand segment size attribute and the operands value range.
3104 llvm::SmallVector<mlir::Value, 6> operands;
3105 llvm::SmallVector<int32_t, 2> operandSegments;
3106
3107 addOperand(operands, operandSegments, deviceNum);
3108 addOperand(operands, operandSegments, ifCond);
3109
3110 Op op =
3111 createSimpleOp<Op>(builder, currentLocation, operands, operandSegments);
3112 if (!deviceTypes.empty())
3113 op.setDeviceTypesAttr(
3114 mlir::ArrayAttr::get(builder.getContext(), deviceTypes));
3115 }
3116
3117 void genACCSetOp(Fortran::lower::AbstractConverter &converter,
3118 mlir::Location currentLocation,
3119 const Fortran::parser::AccClauseList &accClauseList) {
3120 mlir::Value ifCond, deviceNum, defaultAsync;
3121 llvm::SmallVector<mlir::Value> deviceTypeOperands;
3122
3123 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
3124 Fortran::lower::StatementContext stmtCtx;
3125 llvm::SmallVector<mlir::Attribute> deviceTypes;
3126
3127 // Lower clauses values mapped to operands.
3128 // Keep track of each group of operands separately as clauses can appear
3129 // more than once.
3130 for (const Fortran::parser::AccClause &clause : accClauseList.v) {
3131 mlir::Location clauseLocation = converter.genLocation(clause.source);
3132 if (const auto *ifClause =
3133 std::get_if<Fortran::parser::AccClause::If>(&clause.u)) {
3134 genIfClause(converter, clauseLocation, ifClause, ifCond, stmtCtx);
3135 } else if (const auto *defaultAsyncClause =
3136 std::get_if<Fortran::parser::AccClause::DefaultAsync>(
3137 &clause.u)) {
3138 defaultAsync = fir::getBase(converter.genExprValue(
3139 *Fortran::semantics::GetExpr(defaultAsyncClause->v), stmtCtx));
3140 } else if (const auto *deviceNumClause =
3141 std::get_if<Fortran::parser::AccClause::DeviceNum>(
3142 &clause.u)) {
3143 deviceNum = fir::getBase(converter.genExprValue(
3144 *Fortran::semantics::GetExpr(deviceNumClause->v), stmtCtx));
3145 } else if (const auto *deviceTypeClause =
3146 std::get_if<Fortran::parser::AccClause::DeviceType>(
3147 &clause.u)) {
3148 gatherDeviceTypeAttrs(builder, deviceTypeClause, deviceTypes);
3149 }
3150 }
3151
3152 // Prepare the operand segment size attribute and the operands value range.
3153 llvm::SmallVector<mlir::Value> operands;
3154 llvm::SmallVector<int32_t, 3> operandSegments;
3155 addOperand(operands, operandSegments, defaultAsync);
3156 addOperand(operands, operandSegments, deviceNum);
3157 addOperand(operands, operandSegments, ifCond);
3158
3159 auto op = createSimpleOp<mlir::acc::SetOp>(builder, currentLocation, operands,
3160 operandSegments);
3161 if (!deviceTypes.empty()) {
3162 assert(deviceTypes.size() == 1 && "expect only one value for acc.set");
3163 op.setDeviceTypeAttr(mlir::cast<mlir::acc::DeviceTypeAttr>(deviceTypes[0]));
3164 }
3165 }
3166
3167 static inline mlir::ArrayAttr
3168 getArrayAttr(fir::FirOpBuilder &b,
3169 llvm::SmallVector<mlir::Attribute> &attributes) {
3170 return attributes.empty() ? nullptr : b.getArrayAttr(attributes);
3171 }
3172
3173 static inline mlir::ArrayAttr
3174 getBoolArrayAttr(fir::FirOpBuilder &b, llvm::SmallVector<bool> &values) {
3175 return values.empty() ? nullptr : b.getBoolArrayAttr(values);
3176 }
3177
3178 static inline mlir::DenseI32ArrayAttr
3179 getDenseI32ArrayAttr(fir::FirOpBuilder &builder,
3180 llvm::SmallVector<int32_t> &values) {
3181 return values.empty() ? nullptr : builder.getDenseI32ArrayAttr(values);
3182 }
3183
3184 static void
3185 genACCUpdateOp(Fortran::lower::AbstractConverter &converter,
3186 mlir::Location currentLocation,
3187 Fortran::semantics::SemanticsContext &semanticsContext,
3188 Fortran::lower::StatementContext &stmtCtx,
3189 const Fortran::parser::AccClauseList &accClauseList) {
3190 mlir::Value ifCond;
3191 llvm::SmallVector<mlir::Value> dataClauseOperands, updateHostOperands,
3192 waitOperands, deviceTypeOperands, asyncOperands;
3193 llvm::SmallVector<mlir::Attribute> asyncOperandsDeviceTypes,
3194 asyncOnlyDeviceTypes, waitOperandsDeviceTypes, waitOnlyDeviceTypes;
3195 llvm::SmallVector<bool> hasWaitDevnums;
3196 llvm::SmallVector<int32_t> waitOperandsSegments;
3197
3198 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
3199
3200 // device_type attribute is set to `none` until a device_type clause is
3201 // encountered.
3202 llvm::SmallVector<mlir::Attribute> crtDeviceTypes;
3203 crtDeviceTypes.push_back(mlir::acc::DeviceTypeAttr::get(
3204 builder.getContext(), mlir::acc::DeviceType::None));
3205
3206 bool ifPresent = false;
3207
3208 // Lower clauses values mapped to operands and array attributes.
3209 // Keep track of each group of operands separately as clauses can appear
3210 // more than once.
3211
3212 // Process the clauses that may have a specified device_type first.
3213 for (const Fortran::parser::AccClause &clause : accClauseList.v) {
3214 if (const auto *asyncClause =
3215 std::get_if<Fortran::parser::AccClause::Async>(&clause.u)) {
3216 genAsyncClause(converter, asyncClause, asyncOperands,
3217 asyncOperandsDeviceTypes, asyncOnlyDeviceTypes,
3218 crtDeviceTypes, stmtCtx);
3219 } else if (const auto *waitClause =
3220 std::get_if<Fortran::parser::AccClause::Wait>(&clause.u)) {
3221 genWaitClauseWithDeviceType(converter, waitClause, waitOperands,
3222 waitOperandsDeviceTypes, waitOnlyDeviceTypes,
3223 hasWaitDevnums, waitOperandsSegments,
3224 crtDeviceTypes, stmtCtx);
3225 } else if (const auto *deviceTypeClause =
3226 std::get_if<Fortran::parser::AccClause::DeviceType>(
3227 &clause.u)) {
3228 crtDeviceTypes.clear();
3229 gatherDeviceTypeAttrs(builder, deviceTypeClause, crtDeviceTypes);
3230 }
3231 }
3232
3233 // Process the clauses independent of device_type.
3234 for (const Fortran::parser::AccClause &clause : accClauseList.v) {
3235 mlir::Location clauseLocation = converter.genLocation(clause.source);
3236 if (const auto *ifClause =
3237 std::get_if<Fortran::parser::AccClause::If>(&clause.u)) {
3238 genIfClause(converter, clauseLocation, ifClause, ifCond, stmtCtx);
3239 } else if (const auto *hostClause =
3240 std::get_if<Fortran::parser::AccClause::Host>(&clause.u)) {
3241 genDataOperandOperations<mlir::acc::GetDevicePtrOp>(
3242 hostClause->v, converter, semanticsContext, stmtCtx,
3243 updateHostOperands, mlir::acc::DataClause::acc_update_host, false,
3244 /*implicit=*/false, asyncOperands, asyncOperandsDeviceTypes,
3245 asyncOnlyDeviceTypes);
3246 } else if (const auto *deviceClause =
3247 std::get_if<Fortran::parser::AccClause::Device>(&clause.u)) {
3248 genDataOperandOperations<mlir::acc::UpdateDeviceOp>(
3249 deviceClause->v, converter, semanticsContext, stmtCtx,
3250 dataClauseOperands, mlir::acc::DataClause::acc_update_device, false,
3251 /*implicit=*/false, asyncOperands, asyncOperandsDeviceTypes,
3252 asyncOnlyDeviceTypes);
3253 } else if (std::get_if<Fortran::parser::AccClause::IfPresent>(&clause.u)) {
3254 ifPresent = true;
3255 } else if (const auto *selfClause =
3256 std::get_if<Fortran::parser::AccClause::Self>(&clause.u)) {
3257 const std::optional<Fortran::parser::AccSelfClause> &accSelfClause =
3258 selfClause->v;
3259 const auto *accObjectList =
3260 std::get_if<Fortran::parser::AccObjectList>(&(*accSelfClause).u);
3261 assert(accObjectList && "expect AccObjectList");
3262 genDataOperandOperations<mlir::acc::GetDevicePtrOp>(
3263 *accObjectList, converter, semanticsContext, stmtCtx,
3264 updateHostOperands, mlir::acc::DataClause::acc_update_self, false,
3265 /*implicit=*/false, asyncOperands, asyncOperandsDeviceTypes,
3266 asyncOnlyDeviceTypes);
3267 }
3268 }
3269
3270 dataClauseOperands.append(updateHostOperands);
3271
3272 builder.create<mlir::acc::UpdateOp>(
3273 currentLocation, ifCond, asyncOperands,
3274 getArrayAttr(builder, asyncOperandsDeviceTypes),
3275 getArrayAttr(builder, asyncOnlyDeviceTypes), waitOperands,
3276 getDenseI32ArrayAttr(builder, waitOperandsSegments),
3277 getArrayAttr(builder, waitOperandsDeviceTypes),
3278 getBoolArrayAttr(builder, hasWaitDevnums),
3279 getArrayAttr(builder, waitOnlyDeviceTypes), dataClauseOperands,
3280 ifPresent);
3281
3282 genDataExitOperations<mlir::acc::GetDevicePtrOp, mlir::acc::UpdateHostOp>(
3283 builder, updateHostOperands, /*structured=*/false);
3284 }
3285
3286 static void
3287 genACC(Fortran::lower::AbstractConverter &converter,
3288 Fortran::semantics::SemanticsContext &semanticsContext,
3289 const Fortran::parser::OpenACCStandaloneConstruct &standaloneConstruct) {
3290 const auto &standaloneDirective =
3291 std::get<Fortran::parser::AccStandaloneDirective>(standaloneConstruct.t);
3292 const auto &accClauseList =
3293 std::get<Fortran::parser::AccClauseList>(standaloneConstruct.t);
3294
3295 mlir::Location currentLocation =
3296 converter.genLocation(standaloneDirective.source);
3297 Fortran::lower::StatementContext stmtCtx;
3298
3299 if (standaloneDirective.v == llvm::acc::Directive::ACCD_enter_data) {
3300 genACCEnterDataOp(converter, currentLocation, semanticsContext, stmtCtx,
3301 accClauseList);
3302 } else if (standaloneDirective.v == llvm::acc::Directive::ACCD_exit_data) {
3303 genACCExitDataOp(converter, currentLocation, semanticsContext, stmtCtx,
3304 accClauseList);
3305 } else if (standaloneDirective.v == llvm::acc::Directive::ACCD_init) {
3306 genACCInitShutdownOp<mlir::acc::InitOp>(converter, currentLocation,
3307 accClauseList);
3308 } else if (standaloneDirective.v == llvm::acc::Directive::ACCD_shutdown) {
3309 genACCInitShutdownOp<mlir::acc::ShutdownOp>(converter, currentLocation,
3310 accClauseList);
3311 } else if (standaloneDirective.v == llvm::acc::Directive::ACCD_set) {
3312 genACCSetOp(converter, currentLocation, accClauseList);
3313 } else if (standaloneDirective.v == llvm::acc::Directive::ACCD_update) {
3314 genACCUpdateOp(converter, currentLocation, semanticsContext, stmtCtx,
3315 accClauseList);
3316 }
3317 }
3318
3319 static void genACC(Fortran::lower::AbstractConverter &converter,
3320 const Fortran::parser::OpenACCWaitConstruct &waitConstruct) {
3321
3322 const auto &waitArgument =
3323 std::get<std::optional<Fortran::parser::AccWaitArgument>>(
3324 waitConstruct.t);
3325 const auto &accClauseList =
3326 std::get<Fortran::parser::AccClauseList>(waitConstruct.t);
3327
3328 mlir::Value ifCond, waitDevnum, async;
3329 llvm::SmallVector<mlir::Value> waitOperands;
3330
3331 // Async clause have optional values but can be present with
3332 // no value as well. When there is no value, the op has an attribute to
3333 // represent the clause.
3334 bool addAsyncAttr = false;
3335
3336 fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
3337 mlir::Location currentLocation = converter.genLocation(waitConstruct.source);
3338 Fortran::lower::StatementContext stmtCtx;
3339
3340 if (waitArgument) { // wait has a value.
3341 const Fortran::parser::AccWaitArgument &waitArg = *waitArgument;
3342 const auto &waitList =
3343 std::get<std::list<Fortran::parser::ScalarIntExpr>>(waitArg.t);
3344 for (const Fortran::parser::ScalarIntExpr &value : waitList) {
3345 mlir::Value v = fir::getBase(
3346 converter.genExprValue(*Fortran::semantics::GetExpr(value), stmtCtx));
3347 waitOperands.push_back(v);
3348 }
3349
3350 const auto &waitDevnumValue =
3351 std::get<std::optional<Fortran::parser::ScalarIntExpr>>(waitArg.t);
3352 if (waitDevnumValue)
3353 waitDevnum = fir::getBase(converter.genExprValue(
3354 *Fortran::semantics::GetExpr(*waitDevnumValue), stmtCtx));
3355 }
3356
3357 // Lower clauses values mapped to operands.
3358 // Keep track of each group of operands separately as clauses can appear
3359 // more than once.
3360 for (const Fortran::parser::AccClause &clause : accClauseList.v) {
3361 mlir::Location clauseLocation = converter.genLocation(clause.source);
3362 if (const auto *ifClause =
3363 std::get_if<Fortran::parser::AccClause::If>(&clause.u)) {
3364 genIfClause(converter, clauseLocation, ifClause, ifCond, stmtCtx);
3365 } else if (const auto *asyncClause =
3366 std::get_if<Fortran::parser::AccClause::Async>(&clause.u)) {
3367 genAsyncClause(converter, asyncClause, async, addAsyncAttr, stmtCtx);
3368 }
3369 }
3370
3371 // Prepare the operand segment size attribute and the operands value range.
3372 llvm::SmallVector<mlir::Value> operands;
3373 llvm::SmallVector<int32_t> operandSegments;
3374 addOperands(operands, operandSegments, waitOperands);
3375 addOperand(operands, operandSegments, async);
3376 addOperand(operands, operandSegments, waitDevnum);
3377 addOperand(operands, operandSegments, ifCond);
3378
3379 mlir::acc::WaitOp waitOp = createSimpleOp<mlir::acc::WaitOp>(
3380 firOpBuilder, currentLocation, operands, operandSegments);
3381
3382 if (addAsyncAttr)
3383 waitOp.setAsyncAttr(firOpBuilder.getUnitAttr());
3384 }
3385
3386 template <typename GlobalOp, typename EntryOp, typename DeclareOp,
3387 typename ExitOp>
3388 static void createDeclareGlobalOp(mlir::OpBuilder &modBuilder,
3389 fir::FirOpBuilder &builder,
3390 mlir::Location loc, fir::GlobalOp globalOp,
3391 mlir::acc::DataClause clause,
3392 const std::string &declareGlobalName,
3393 bool implicit, std::stringstream &asFortran) {
3394 GlobalOp declareGlobalOp =
3395 modBuilder.create<GlobalOp>(loc, declareGlobalName);
3396 builder.createBlock(&declareGlobalOp.getRegion(),
3397 declareGlobalOp.getRegion().end(), {}, {});
3398 builder.setInsertionPointToEnd(&declareGlobalOp.getRegion().back());
3399
3400 fir::AddrOfOp addrOp = builder.create<fir::AddrOfOp>(
3401 loc, fir::ReferenceType::get(globalOp.getType()), globalOp.getSymbol());
3402 addDeclareAttr(builder, addrOp, clause);
3403
3404 llvm::SmallVector<mlir::Value> bounds;
3405 EntryOp entryOp = createDataEntryOp<EntryOp>(
3406 builder, loc, addrOp.getResTy(), asFortran, bounds,
3407 /*structured=*/false, implicit, clause, addrOp.getResTy().getType(),
3408 /*async=*/{}, /*asyncDeviceTypes=*/{}, /*asyncOnlyDeviceTypes=*/{});
3409 if constexpr (std::is_same_v<DeclareOp, mlir::acc::DeclareEnterOp>)
3410 builder.create<DeclareOp>(
3411 loc, mlir::acc::DeclareTokenType::get(entryOp.getContext()),
3412 mlir::ValueRange(entryOp.getAccPtr()));
3413 else
3414 builder.create<DeclareOp>(loc, mlir::Value{},
3415 mlir::ValueRange(entryOp.getAccPtr()));
3416 if constexpr (std::is_same_v<GlobalOp, mlir::acc::GlobalDestructorOp>) {
3417 builder.create<ExitOp>(entryOp.getLoc(), entryOp.getAccPtr(),
3418 entryOp.getBounds(), entryOp.getAsyncOperands(),
3419 entryOp.getAsyncOperandsDeviceTypeAttr(),
3420 entryOp.getAsyncOnlyAttr(), entryOp.getDataClause(),
3421 /*structured=*/false, /*implicit=*/false,
3422 builder.getStringAttr(*entryOp.getName()));
3423 }
3424 builder.create<mlir::acc::TerminatorOp>(loc);
3425 modBuilder.setInsertionPointAfter(declareGlobalOp);
3426 }
3427
3428 template <typename EntryOp>
3429 static void createDeclareAllocFunc(mlir::OpBuilder &modBuilder,
3430 fir::FirOpBuilder &builder,
3431 mlir::Location loc, fir::GlobalOp &globalOp,
3432 mlir::acc::DataClause clause) {
3433 std::stringstream registerFuncName;
3434 registerFuncName << globalOp.getSymName().str()
3435 << Fortran::lower::declarePostAllocSuffix.str();
3436 auto registerFuncOp =
3437 createDeclareFunc(modBuilder, builder, loc, registerFuncName.str());
3438
3439 fir::AddrOfOp addrOp = builder.create<fir::AddrOfOp>(
3440 loc, fir::ReferenceType::get(globalOp.getType()), globalOp.getSymbol());
3441
3442 std::stringstream asFortran;
3443 asFortran << Fortran::lower::mangle::demangleName(globalOp.getSymName());
3444 std::stringstream asFortranDesc;
3445 asFortranDesc << asFortran.str() << accFirDescriptorPostfix.str();
3446 llvm::SmallVector<mlir::Value> bounds;
3447
3448 // Updating descriptor must occur before the mapping of the data so that
3449 // attached data pointer is not overwritten.
3450 mlir::acc::UpdateDeviceOp updateDeviceOp =
3451 createDataEntryOp<mlir::acc::UpdateDeviceOp>(
3452 builder, loc, addrOp, asFortranDesc, bounds,
3453 /*structured=*/false, /*implicit=*/true,
3454 mlir::acc::DataClause::acc_update_device, addrOp.getType(),
3455 /*async=*/{}, /*asyncDeviceTypes=*/{}, /*asyncOnlyDeviceTypes=*/{});
3456 llvm::SmallVector<int32_t> operandSegments{0, 0, 0, 1};
3457 llvm::SmallVector<mlir::Value> operands{updateDeviceOp.getResult()};
3458 createSimpleOp<mlir::acc::UpdateOp>(builder, loc, operands, operandSegments);
3459
3460 auto loadOp = builder.create<fir::LoadOp>(loc, addrOp.getResult());
3461 fir::BoxAddrOp boxAddrOp = builder.create<fir::BoxAddrOp>(loc, loadOp);
3462 addDeclareAttr(builder, boxAddrOp.getOperation(), clause);
3463 EntryOp entryOp = createDataEntryOp<EntryOp>(
3464 builder, loc, boxAddrOp.getResult(), asFortran, bounds,
3465 /*structured=*/false, /*implicit=*/false, clause, boxAddrOp.getType(),
3466 /*async=*/{}, /*asyncDeviceTypes=*/{}, /*asyncOnlyDeviceTypes=*/{});
3467 builder.create<mlir::acc::DeclareEnterOp>(
3468 loc, mlir::acc::DeclareTokenType::get(entryOp.getContext()),
3469 mlir::ValueRange(entryOp.getAccPtr()));
3470
3471 modBuilder.setInsertionPointAfter(registerFuncOp);
3472 }
3473
3474 /// Action to be performed on deallocation are split in two distinct functions.
3475 /// - Pre deallocation function includes all the action to be performed before
3476 /// the actual deallocation is done on the host side.
3477 /// - Post deallocation function includes update to the descriptor.
3478 template <typename ExitOp>
3479 static void createDeclareDeallocFunc(mlir::OpBuilder &modBuilder,
3480 fir::FirOpBuilder &builder,
3481 mlir::Location loc,
3482 fir::GlobalOp &globalOp,
3483 mlir::acc::DataClause clause) {
3484
3485 // Generate the pre dealloc function.
3486 std::stringstream preDeallocFuncName;
3487 preDeallocFuncName << globalOp.getSymName().str()
3488 << Fortran::lower::declarePreDeallocSuffix.str();
3489 auto preDeallocOp =
3490 createDeclareFunc(modBuilder, builder, loc, preDeallocFuncName.str());
3491 fir::AddrOfOp addrOp = builder.create<fir::AddrOfOp>(
3492 loc, fir::ReferenceType::get(globalOp.getType()), globalOp.getSymbol());
3493 auto loadOp = builder.create<fir::LoadOp>(loc, addrOp.getResult());
3494 fir::BoxAddrOp boxAddrOp = builder.create<fir::BoxAddrOp>(loc, loadOp);
3495 addDeclareAttr(builder, boxAddrOp.getOperation(), clause);
3496
3497 std::stringstream asFortran;
3498 asFortran << Fortran::lower::mangle::demangleName(globalOp.getSymName());
3499 llvm::SmallVector<mlir::Value> bounds;
3500 mlir::acc::GetDevicePtrOp entryOp =
3501 createDataEntryOp<mlir::acc::GetDevicePtrOp>(
3502 builder, loc, boxAddrOp.getResult(), asFortran, bounds,
3503 /*structured=*/false, /*implicit=*/false, clause, boxAddrOp.getType(),
3504 /*async=*/{}, /*asyncDeviceTypes=*/{}, /*asyncOnlyDeviceTypes=*/{});
3505
3506 builder.create<mlir::acc::DeclareExitOp>(
3507 loc, mlir::Value{}, mlir::ValueRange(entryOp.getAccPtr()));
3508
3509 if constexpr (std::is_same_v<ExitOp, mlir::acc::CopyoutOp> ||
3510 std::is_same_v<ExitOp, mlir::acc::UpdateHostOp>)
3511 builder.create<ExitOp>(entryOp.getLoc(), entryOp.getAccPtr(),
3512 entryOp.getVarPtr(), entryOp.getBounds(),
3513 entryOp.getAsyncOperands(),
3514 entryOp.getAsyncOperandsDeviceTypeAttr(),
3515 entryOp.getAsyncOnlyAttr(), entryOp.getDataClause(),
3516 /*structured=*/false, /*implicit=*/false,
3517 builder.getStringAttr(*entryOp.getName()));
3518 else
3519 builder.create<ExitOp>(entryOp.getLoc(), entryOp.getAccPtr(),
3520 entryOp.getBounds(), entryOp.getAsyncOperands(),
3521 entryOp.getAsyncOperandsDeviceTypeAttr(),
3522 entryOp.getAsyncOnlyAttr(), entryOp.getDataClause(),
3523 /*structured=*/false, /*implicit=*/false,
3524 builder.getStringAttr(*entryOp.getName()));
3525
3526 // Generate the post dealloc function.
3527 modBuilder.setInsertionPointAfter(preDeallocOp);
3528 std::stringstream postDeallocFuncName;
3529 postDeallocFuncName << globalOp.getSymName().str()
3530 << Fortran::lower::declarePostDeallocSuffix.str();
3531 auto postDeallocOp =
3532 createDeclareFunc(modBuilder, builder, loc, postDeallocFuncName.str());
3533
3534 addrOp = builder.create<fir::AddrOfOp>(
3535 loc, fir::ReferenceType::get(globalOp.getType()), globalOp.getSymbol());
3536 asFortran << accFirDescriptorPostfix.str();
3537 mlir::acc::UpdateDeviceOp updateDeviceOp =
3538 createDataEntryOp<mlir::acc::UpdateDeviceOp>(
3539 builder, loc, addrOp, asFortran, bounds,
3540 /*structured=*/false, /*implicit=*/true,
3541 mlir::acc::DataClause::acc_update_device, addrOp.getType(),
3542 /*async=*/{}, /*asyncDeviceTypes=*/{}, /*asyncOnlyDeviceTypes=*/{});
3543 llvm::SmallVector<int32_t> operandSegments{0, 0, 0, 1};
3544 llvm::SmallVector<mlir::Value> operands{updateDeviceOp.getResult()};
3545 createSimpleOp<mlir::acc::UpdateOp>(builder, loc, operands, operandSegments);
3546 modBuilder.setInsertionPointAfter(postDeallocOp);
3547 }
3548
3549 template <typename EntryOp, typename ExitOp>
3550 static void genGlobalCtors(Fortran::lower::AbstractConverter &converter,
3551 mlir::OpBuilder &modBuilder,
3552 const Fortran::parser::AccObjectList &accObjectList,
3553 mlir::acc::DataClause clause) {
3554 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
3555 for (const auto &accObject : accObjectList.v) {
3556 mlir::Location operandLocation = genOperandLocation(converter, accObject);
3557 Fortran::common::visit(
3558 Fortran::common::visitors{
3559 [&](const Fortran::parser::Designator &designator) {
3560 if (const auto *name =
3561 Fortran::semantics::getDesignatorNameIfDataRef(
3562 designator)) {
3563 std::string globalName = converter.mangleName(*name->symbol);
3564 fir::GlobalOp globalOp = builder.getNamedGlobal(globalName);
3565 std::stringstream declareGlobalCtorName;
3566 declareGlobalCtorName << globalName << "_acc_ctor";
3567 std::stringstream declareGlobalDtorName;
3568 declareGlobalDtorName << globalName << "_acc_dtor";
3569 std::stringstream asFortran;
3570 asFortran << name->symbol->name().ToString();
3571
3572 if (builder.getModule()
3573 .lookupSymbol<mlir::acc::GlobalConstructorOp>(
3574 declareGlobalCtorName.str()))
3575 return;
3576
3577 if (!globalOp) {
3578 if (Fortran::semantics::FindEquivalenceSet(*name->symbol)) {
3579 for (Fortran::semantics::EquivalenceObject eqObj :
3580 *Fortran::semantics::FindEquivalenceSet(
3581 *name->symbol)) {
3582 std::string eqName = converter.mangleName(eqObj.symbol);
3583 globalOp = builder.getNamedGlobal(eqName);
3584 if (globalOp)
3585 break;
3586 }
3587
3588 if (!globalOp)
3589 llvm::report_fatal_error(
3590 "could not retrieve global symbol");
3591 } else {
3592 llvm::report_fatal_error(
3593 "could not retrieve global symbol");
3594 }
3595 }
3596
3597 addDeclareAttr(builder, globalOp.getOperation(), clause);
3598 auto crtPos = builder.saveInsertionPoint();
3599 modBuilder.setInsertionPointAfter(globalOp);
3600 if (mlir::isa<fir::BaseBoxType>(
3601 fir::unwrapRefType(globalOp.getType()))) {
3602 createDeclareGlobalOp<mlir::acc::GlobalConstructorOp,
3603 mlir::acc::CopyinOp,
3604 mlir::acc::DeclareEnterOp, ExitOp>(
3605 modBuilder, builder, operandLocation, globalOp, clause,
3606 declareGlobalCtorName.str(), /*implicit=*/true,
3607 asFortran);
3608 createDeclareAllocFunc<EntryOp>(
3609 modBuilder, builder, operandLocation, globalOp, clause);
3610 if constexpr (!std::is_same_v<EntryOp, ExitOp>)
3611 createDeclareDeallocFunc<ExitOp>(
3612 modBuilder, builder, operandLocation, globalOp, clause);
3613 } else {
3614 createDeclareGlobalOp<mlir::acc::GlobalConstructorOp, EntryOp,
3615 mlir::acc::DeclareEnterOp, ExitOp>(
3616 modBuilder, builder, operandLocation, globalOp, clause,
3617 declareGlobalCtorName.str(), /*implicit=*/false,
3618 asFortran);
3619 }
3620 if constexpr (!std::is_same_v<EntryOp, ExitOp>) {
3621 createDeclareGlobalOp<mlir::acc::GlobalDestructorOp,
3622 mlir::acc::GetDevicePtrOp,
3623 mlir::acc::DeclareExitOp, ExitOp>(
3624 modBuilder, builder, operandLocation, globalOp, clause,
3625 declareGlobalDtorName.str(), /*implicit=*/false,
3626 asFortran);
3627 }
3628 builder.restoreInsertionPoint(crtPos);
3629 }
3630 },
3631 [&](const Fortran::parser::Name &name) {
3632 TODO(operandLocation, "OpenACC Global Ctor from parser::Name");
3633 }},
3634 accObject.u);
3635 }
3636 }
3637
3638 template <typename Clause, typename EntryOp, typename ExitOp>
3639 static void
3640 genGlobalCtorsWithModifier(Fortran::lower::AbstractConverter &converter,
3641 mlir::OpBuilder &modBuilder, const Clause *x,
3642 Fortran::parser::AccDataModifier::Modifier mod,
3643 const mlir::acc::DataClause clause,
3644 const mlir::acc::DataClause clauseWithModifier) {
3645 const Fortran::parser::AccObjectListWithModifier &listWithModifier = x->v;
3646 const auto &accObjectList =
3647 std::get<Fortran::parser::AccObjectList>(listWithModifier.t);
3648 const auto &modifier =
3649 std::get<std::optional<Fortran::parser::AccDataModifier>>(
3650 listWithModifier.t);
3651 mlir::acc::DataClause dataClause =
3652 (modifier && (*modifier).v == mod) ? clauseWithModifier : clause;
3653 genGlobalCtors<EntryOp, ExitOp>(converter, modBuilder, accObjectList,
3654 dataClause);
3655 }
3656
3657 static void
3658 genDeclareInFunction(Fortran::lower::AbstractConverter &converter,
3659 Fortran::semantics::SemanticsContext &semanticsContext,
3660 Fortran::lower::StatementContext &openAccCtx,
3661 mlir::Location loc,
3662 const Fortran::parser::AccClauseList &accClauseList) {
3663 llvm::SmallVector<mlir::Value> dataClauseOperands, copyEntryOperands,
3664 createEntryOperands, copyoutEntryOperands, deviceResidentEntryOperands;
3665 Fortran::lower::StatementContext stmtCtx;
3666 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
3667
3668 for (const Fortran::parser::AccClause &clause : accClauseList.v) {
3669 if (const auto *copyClause =
3670 std::get_if<Fortran::parser::AccClause::Copy>(&clause.u)) {
3671 auto crtDataStart = dataClauseOperands.size();
3672 genDeclareDataOperandOperations<mlir::acc::CopyinOp,
3673 mlir::acc::CopyoutOp>(
3674 copyClause->v, converter, semanticsContext, stmtCtx,
3675 dataClauseOperands, mlir::acc::DataClause::acc_copy,
3676 /*structured=*/true, /*implicit=*/false);
3677 copyEntryOperands.append(dataClauseOperands.begin() + crtDataStart,
3678 dataClauseOperands.end());
3679 } else if (const auto *createClause =
3680 std::get_if<Fortran::parser::AccClause::Create>(&clause.u)) {
3681 const Fortran::parser::AccObjectListWithModifier &listWithModifier =
3682 createClause->v;
3683 const auto &accObjectList =
3684 std::get<Fortran::parser::AccObjectList>(listWithModifier.t);
3685 auto crtDataStart = dataClauseOperands.size();
3686 genDeclareDataOperandOperations<mlir::acc::CreateOp, mlir::acc::DeleteOp>(
3687 accObjectList, converter, semanticsContext, stmtCtx,
3688 dataClauseOperands, mlir::acc::DataClause::acc_create,
3689 /*structured=*/true, /*implicit=*/false);
3690 createEntryOperands.append(dataClauseOperands.begin() + crtDataStart,
3691 dataClauseOperands.end());
3692 } else if (const auto *presentClause =
3693 std::get_if<Fortran::parser::AccClause::Present>(
3694 &clause.u)) {
3695 genDeclareDataOperandOperations<mlir::acc::PresentOp,
3696 mlir::acc::PresentOp>(
3697 presentClause->v, converter, semanticsContext, stmtCtx,
3698 dataClauseOperands, mlir::acc::DataClause::acc_present,
3699 /*structured=*/true, /*implicit=*/false);
3700 } else if (const auto *copyinClause =
3701 std::get_if<Fortran::parser::AccClause::Copyin>(&clause.u)) {
3702 genDeclareDataOperandOperationsWithModifier<mlir::acc::CopyinOp,
3703 mlir::acc::DeleteOp>(
3704 copyinClause, converter, semanticsContext, stmtCtx,
3705 Fortran::parser::AccDataModifier::Modifier::ReadOnly,
3706 dataClauseOperands, mlir::acc::DataClause::acc_copyin,
3707 mlir::acc::DataClause::acc_copyin_readonly);
3708 } else if (const auto *copyoutClause =
3709 std::get_if<Fortran::parser::AccClause::Copyout>(
3710 &clause.u)) {
3711 const Fortran::parser::AccObjectListWithModifier &listWithModifier =
3712 copyoutClause->v;
3713 const auto &accObjectList =
3714 std::get<Fortran::parser::AccObjectList>(listWithModifier.t);
3715 auto crtDataStart = dataClauseOperands.size();
3716 genDeclareDataOperandOperations<mlir::acc::CreateOp,
3717 mlir::acc::CopyoutOp>(
3718 accObjectList, converter, semanticsContext, stmtCtx,
3719 dataClauseOperands, mlir::acc::DataClause::acc_copyout,
3720 /*structured=*/true, /*implicit=*/false);
3721 copyoutEntryOperands.append(dataClauseOperands.begin() + crtDataStart,
3722 dataClauseOperands.end());
3723 } else if (const auto *devicePtrClause =
3724 std::get_if<Fortran::parser::AccClause::Deviceptr>(
3725 &clause.u)) {
3726 genDeclareDataOperandOperations<mlir::acc::DevicePtrOp,
3727 mlir::acc::DevicePtrOp>(
3728 devicePtrClause->v, converter, semanticsContext, stmtCtx,
3729 dataClauseOperands, mlir::acc::DataClause::acc_deviceptr,
3730 /*structured=*/true, /*implicit=*/false);
3731 } else if (const auto *linkClause =
3732 std::get_if<Fortran::parser::AccClause::Link>(&clause.u)) {
3733 genDeclareDataOperandOperations<mlir::acc::DeclareLinkOp,
3734 mlir::acc::DeclareLinkOp>(
3735 linkClause->v, converter, semanticsContext, stmtCtx,
3736 dataClauseOperands, mlir::acc::DataClause::acc_declare_link,
3737 /*structured=*/true, /*implicit=*/false);
3738 } else if (const auto *deviceResidentClause =
3739 std::get_if<Fortran::parser::AccClause::DeviceResident>(
3740 &clause.u)) {
3741 auto crtDataStart = dataClauseOperands.size();
3742 genDeclareDataOperandOperations<mlir::acc::DeclareDeviceResidentOp,
3743 mlir::acc::DeleteOp>(
3744 deviceResidentClause->v, converter, semanticsContext, stmtCtx,
3745 dataClauseOperands,
3746 mlir::acc::DataClause::acc_declare_device_resident,
3747 /*structured=*/true, /*implicit=*/false);
3748 deviceResidentEntryOperands.append(
3749 dataClauseOperands.begin() + crtDataStart, dataClauseOperands.end());
3750 } else {
3751 mlir::Location clauseLocation = converter.genLocation(clause.source);
3752 TODO(clauseLocation, "clause on declare directive");
3753 }
3754 }
3755
3756 mlir::func::FuncOp funcOp = builder.getFunction();
3757 auto ops = funcOp.getOps<mlir::acc::DeclareEnterOp>();
3758 mlir::Value declareToken;
3759 if (ops.empty()) {
3760 declareToken = builder.create<mlir::acc::DeclareEnterOp>(
3761 loc, mlir::acc::DeclareTokenType::get(builder.getContext()),
3762 dataClauseOperands);
3763 } else {
3764 auto declareOp = *ops.begin();
3765 auto newDeclareOp = builder.create<mlir::acc::DeclareEnterOp>(
3766 loc, mlir::acc::DeclareTokenType::get(builder.getContext()),
3767 declareOp.getDataClauseOperands());
3768 newDeclareOp.getDataClauseOperandsMutable().append(dataClauseOperands);
3769 declareToken = newDeclareOp.getToken();
3770 declareOp.erase();
3771 }
3772
3773 openAccCtx.attachCleanup([&builder, loc, createEntryOperands,
3774 copyEntryOperands, copyoutEntryOperands,
3775 deviceResidentEntryOperands, declareToken]() {
3776 llvm::SmallVector<mlir::Value> operands;
3777 operands.append(createEntryOperands);
3778 operands.append(deviceResidentEntryOperands);
3779 operands.append(copyEntryOperands);
3780 operands.append(copyoutEntryOperands);
3781
3782 mlir::func::FuncOp funcOp = builder.getFunction();
3783 auto ops = funcOp.getOps<mlir::acc::DeclareExitOp>();
3784 if (ops.empty()) {
3785 builder.create<mlir::acc::DeclareExitOp>(loc, declareToken, operands);
3786 } else {
3787 auto declareOp = *ops.begin();
3788 declareOp.getDataClauseOperandsMutable().append(operands);
3789 }
3790
3791 genDataExitOperations<mlir::acc::CreateOp, mlir::acc::DeleteOp>(
3792 builder, createEntryOperands, /*structured=*/true);
3793 genDataExitOperations<mlir::acc::DeclareDeviceResidentOp,
3794 mlir::acc::DeleteOp>(
3795 builder, deviceResidentEntryOperands, /*structured=*/true);
3796 genDataExitOperations<mlir::acc::CopyinOp, mlir::acc::CopyoutOp>(
3797 builder, copyEntryOperands, /*structured=*/true);
3798 genDataExitOperations<mlir::acc::CreateOp, mlir::acc::CopyoutOp>(
3799 builder, copyoutEntryOperands, /*structured=*/true);
3800 });
3801 }
3802
3803 static void
3804 genDeclareInModule(Fortran::lower::AbstractConverter &converter,
3805 mlir::ModuleOp &moduleOp,
3806 const Fortran::parser::AccClauseList &accClauseList) {
3807 mlir::OpBuilder modBuilder(moduleOp.getBodyRegion());
3808 for (const Fortran::parser::AccClause &clause : accClauseList.v) {
3809 if (const auto *createClause =
3810 std::get_if<Fortran::parser::AccClause::Create>(&clause.u)) {
3811 const Fortran::parser::AccObjectListWithModifier &listWithModifier =
3812 createClause->v;
3813 const auto &accObjectList =
3814 std::get<Fortran::parser::AccObjectList>(listWithModifier.t);
3815 genGlobalCtors<mlir::acc::CreateOp, mlir::acc::DeleteOp>(
3816 converter, modBuilder, accObjectList,
3817 mlir::acc::DataClause::acc_create);
3818 } else if (const auto *copyinClause =
3819 std::get_if<Fortran::parser::AccClause::Copyin>(&clause.u)) {
3820 genGlobalCtorsWithModifier<Fortran::parser::AccClause::Copyin,
3821 mlir::acc::CopyinOp, mlir::acc::CopyinOp>(
3822 converter, modBuilder, copyinClause,
3823 Fortran::parser::AccDataModifier::Modifier::ReadOnly,
3824 mlir::acc::DataClause::acc_copyin,
3825 mlir::acc::DataClause::acc_copyin_readonly);
3826 } else if (const auto *deviceResidentClause =
3827 std::get_if<Fortran::parser::AccClause::DeviceResident>(
3828 &clause.u)) {
3829 genGlobalCtors<mlir::acc::DeclareDeviceResidentOp, mlir::acc::DeleteOp>(
3830 converter, modBuilder, deviceResidentClause->v,
3831 mlir::acc::DataClause::acc_declare_device_resident);
3832 } else if (const auto *linkClause =
3833 std::get_if<Fortran::parser::AccClause::Link>(&clause.u)) {
3834 genGlobalCtors<mlir::acc::DeclareLinkOp, mlir::acc::DeclareLinkOp>(
3835 converter, modBuilder, linkClause->v,
3836 mlir::acc::DataClause::acc_declare_link);
3837 } else {
3838 llvm::report_fatal_error("unsupported clause on DECLARE directive");
3839 }
3840 }
3841 }
3842
3843 static void genACC(Fortran::lower::AbstractConverter &converter,
3844 Fortran::semantics::SemanticsContext &semanticsContext,
3845 Fortran::lower::StatementContext &openAccCtx,
3846 const Fortran::parser::OpenACCStandaloneDeclarativeConstruct
3847 &declareConstruct) {
3848
3849 const auto &declarativeDir =
3850 std::get<Fortran::parser::AccDeclarativeDirective>(declareConstruct.t);
3851 mlir::Location directiveLocation =
3852 converter.genLocation(declarativeDir.source);
3853 const auto &accClauseList =
3854 std::get<Fortran::parser::AccClauseList>(declareConstruct.t);
3855
3856 if (declarativeDir.v == llvm::acc::Directive::ACCD_declare) {
3857 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
3858 auto moduleOp =
3859 builder.getBlock()->getParent()->getParentOfType<mlir::ModuleOp>();
3860 auto funcOp =
3861 builder.getBlock()->getParent()->getParentOfType<mlir::func::FuncOp>();
3862 if (funcOp)
3863 genDeclareInFunction(converter, semanticsContext, openAccCtx,
3864 directiveLocation, accClauseList);
3865 else if (moduleOp)
3866 genDeclareInModule(converter, moduleOp, accClauseList);
3867 return;
3868 }
3869 llvm_unreachable("unsupported declarative directive");
3870 }
3871
3872 static bool hasDeviceType(llvm::SmallVector<mlir::Attribute> &arrayAttr,
3873 mlir::acc::DeviceType deviceType) {
3874 for (auto attr : arrayAttr) {
3875 auto deviceTypeAttr = mlir::dyn_cast<mlir::acc::DeviceTypeAttr>(attr);
3876 if (deviceTypeAttr.getValue() == deviceType)
3877 return true;
3878 }
3879 return false;
3880 }
3881
3882 template <typename RetTy, typename AttrTy>
3883 static std::optional<RetTy>
3884 getAttributeValueByDeviceType(llvm::SmallVector<mlir::Attribute> &attributes,
3885 llvm::SmallVector<mlir::Attribute> &deviceTypes,
3886 mlir::acc::DeviceType deviceType) {
3887 assert(attributes.size() == deviceTypes.size() &&
3888 "expect same number of attributes");
3889 for (auto it : llvm::enumerate(deviceTypes)) {
3890 auto deviceTypeAttr = mlir::dyn_cast<mlir::acc::DeviceTypeAttr>(it.value());
3891 if (deviceTypeAttr.getValue() == deviceType) {
3892 if constexpr (std::is_same_v<mlir::StringAttr, AttrTy>) {
3893 auto strAttr = mlir::dyn_cast<AttrTy>(attributes[it.index()]);
3894 return strAttr.getValue();
3895 } else if constexpr (std::is_same_v<mlir::IntegerAttr, AttrTy>) {
3896 auto intAttr =
3897 mlir::dyn_cast<mlir::IntegerAttr>(attributes[it.index()]);
3898 return intAttr.getInt();
3899 }
3900 }
3901 }
3902 return std::nullopt;
3903 }
3904
3905 static bool compareDeviceTypeInfo(
3906 mlir::acc::RoutineOp op,
3907 llvm::SmallVector<mlir::Attribute> &bindNameArrayAttr,
3908 llvm::SmallVector<mlir::Attribute> &bindNameDeviceTypeArrayAttr,
3909 llvm::SmallVector<mlir::Attribute> &gangArrayAttr,
3910 llvm::SmallVector<mlir::Attribute> &gangDimArrayAttr,
3911 llvm::SmallVector<mlir::Attribute> &gangDimDeviceTypeArrayAttr,
3912 llvm::SmallVector<mlir::Attribute> &seqArrayAttr,
3913 llvm::SmallVector<mlir::Attribute> &workerArrayAttr,
3914 llvm::SmallVector<mlir::Attribute> &vectorArrayAttr) {
3915 for (uint32_t dtypeInt = 0;
3916 dtypeInt != mlir::acc::getMaxEnumValForDeviceType(); ++dtypeInt) {
3917 auto dtype = static_cast<mlir::acc::DeviceType>(dtypeInt);
3918 if (op.getBindNameValue(dtype) !=
3919 getAttributeValueByDeviceType<llvm::StringRef, mlir::StringAttr>(
3920 bindNameArrayAttr, bindNameDeviceTypeArrayAttr, dtype))
3921 return false;
3922 if (op.hasGang(dtype) != hasDeviceType(gangArrayAttr, dtype))
3923 return false;
3924 if (op.getGangDimValue(dtype) !=
3925 getAttributeValueByDeviceType<int64_t, mlir::IntegerAttr>(
3926 gangDimArrayAttr, gangDimDeviceTypeArrayAttr, dtype))
3927 return false;
3928 if (op.hasSeq(dtype) != hasDeviceType(seqArrayAttr, dtype))
3929 return false;
3930 if (op.hasWorker(dtype) != hasDeviceType(workerArrayAttr, dtype))
3931 return false;
3932 if (op.hasVector(dtype) != hasDeviceType(vectorArrayAttr, dtype))
3933 return false;
3934 }
3935 return true;
3936 }
3937
3938 static void attachRoutineInfo(mlir::func::FuncOp func,
3939 mlir::SymbolRefAttr routineAttr) {
3940 llvm::SmallVector<mlir::SymbolRefAttr> routines;
3941 if (func.getOperation()->hasAttr(mlir::acc::getRoutineInfoAttrName())) {
3942 auto routineInfo =
3943 func.getOperation()->getAttrOfType<mlir::acc::RoutineInfoAttr>(
3944 mlir::acc::getRoutineInfoAttrName());
3945 routines.append(routineInfo.getAccRoutines().begin(),
3946 routineInfo.getAccRoutines().end());
3947 }
3948 routines.push_back(routineAttr);
3949 func.getOperation()->setAttr(
3950 mlir::acc::getRoutineInfoAttrName(),
3951 mlir::acc::RoutineInfoAttr::get(func.getContext(), routines));
3952 }
3953
3954 void Fortran::lower::genOpenACCRoutineConstruct(
3955 Fortran::lower::AbstractConverter &converter,
3956 Fortran::semantics::SemanticsContext &semanticsContext, mlir::ModuleOp &mod,
3957 const Fortran::parser::OpenACCRoutineConstruct &routineConstruct,
3958 Fortran::lower::AccRoutineInfoMappingList &accRoutineInfos) {
3959 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
3960 mlir::Location loc = converter.genLocation(routineConstruct.source);
3961 std::optional<Fortran::parser::Name> name =
3962 std::get<std::optional<Fortran::parser::Name>>(routineConstruct.t);
3963 const auto &clauses =
3964 std::get<Fortran::parser::AccClauseList>(routineConstruct.t);
3965 mlir::func::FuncOp funcOp;
3966 std::string funcName;
3967 if (name) {
3968 funcName = converter.mangleName(*name->symbol);
3969 funcOp =
3970 builder.getNamedFunction(mod, builder.getMLIRSymbolTable(), funcName);
3971 } else {
3972 Fortran::semantics::Scope &scope =
3973 semanticsContext.FindScope(routineConstruct.source);
3974 const Fortran::semantics::Scope &progUnit{GetProgramUnitContaining(scope)};
3975 const auto *subpDetails{
3976 progUnit.symbol()
3977 ? progUnit.symbol()
3978 ->detailsIf<Fortran::semantics::SubprogramDetails>()
3979 : nullptr};
3980 if (subpDetails && subpDetails->isInterface()) {
3981 funcName = converter.mangleName(*progUnit.symbol());
3982 funcOp =
3983 builder.getNamedFunction(mod, builder.getMLIRSymbolTable(), funcName);
3984 } else {
3985 funcOp = builder.getFunction();
3986 funcName = funcOp.getName();
3987 }
3988 }
3989 bool hasNohost = false;
3990
3991 llvm::SmallVector<mlir::Attribute> seqDeviceTypes, vectorDeviceTypes,
3992 workerDeviceTypes, bindNameDeviceTypes, bindNames, gangDeviceTypes,
3993 gangDimDeviceTypes, gangDimValues;
3994
3995 // device_type attribute is set to `none` until a device_type clause is
3996 // encountered.
3997 llvm::SmallVector<mlir::Attribute> crtDeviceTypes;
3998 crtDeviceTypes.push_back(mlir::acc::DeviceTypeAttr::get(
3999 builder.getContext(), mlir::acc::DeviceType::None));
4000
4001 for (const Fortran::parser::AccClause &clause : clauses.v) {
4002 if (std::get_if<Fortran::parser::AccClause::Seq>(&clause.u)) {
4003 for (auto crtDeviceTypeAttr : crtDeviceTypes)
4004 seqDeviceTypes.push_back(crtDeviceTypeAttr);
4005 } else if (const auto *gangClause =
4006 std::get_if<Fortran::parser::AccClause::Gang>(&clause.u)) {
4007 if (gangClause->v) {
4008 const Fortran::parser::AccGangArgList &x = *gangClause->v;
4009 for (const Fortran::parser::AccGangArg &gangArg : x.v) {
4010 if (const auto *dim =
4011 std::get_if<Fortran::parser::AccGangArg::Dim>(&gangArg.u)) {
4012 const std::optional<int64_t> dimValue = Fortran::evaluate::ToInt64(
4013 *Fortran::semantics::GetExpr(dim->v));
4014 if (!dimValue)
4015 mlir::emitError(loc,
4016 "dim value must be a constant positive integer");
4017 mlir::Attribute gangDimAttr =
4018 builder.getIntegerAttr(builder.getI64Type(), *dimValue);
4019 for (auto crtDeviceTypeAttr : crtDeviceTypes) {
4020 gangDimValues.push_back(gangDimAttr);
4021 gangDimDeviceTypes.push_back(crtDeviceTypeAttr);
4022 }
4023 }
4024 }
4025 } else {
4026 for (auto crtDeviceTypeAttr : crtDeviceTypes)
4027 gangDeviceTypes.push_back(crtDeviceTypeAttr);
4028 }
4029 } else if (std::get_if<Fortran::parser::AccClause::Vector>(&clause.u)) {
4030 for (auto crtDeviceTypeAttr : crtDeviceTypes)
4031 vectorDeviceTypes.push_back(crtDeviceTypeAttr);
4032 } else if (std::get_if<Fortran::parser::AccClause::Worker>(&clause.u)) {
4033 for (auto crtDeviceTypeAttr : crtDeviceTypes)
4034 workerDeviceTypes.push_back(crtDeviceTypeAttr);
4035 } else if (std::get_if<Fortran::parser::AccClause::Nohost>(&clause.u)) {
4036 hasNohost = true;
4037 } else if (const auto *bindClause =
4038 std::get_if<Fortran::parser::AccClause::Bind>(&clause.u)) {
4039 if (const auto *name =
4040 std::get_if<Fortran::parser::Name>(&bindClause->v.u)) {
4041 mlir::Attribute bindNameAttr =
4042 builder.getStringAttr(converter.mangleName(*name->symbol));
4043 for (auto crtDeviceTypeAttr : crtDeviceTypes) {
4044 bindNames.push_back(bindNameAttr);
4045 bindNameDeviceTypes.push_back(crtDeviceTypeAttr);
4046 }
4047 } else if (const auto charExpr =
4048 std::get_if<Fortran::parser::ScalarDefaultCharExpr>(
4049 &bindClause->v.u)) {
4050 const std::optional<std::string> name =
4051 Fortran::semantics::GetConstExpr<std::string>(semanticsContext,
4052 *charExpr);
4053 if (!name)
4054 mlir::emitError(loc, "Could not retrieve the bind name");
4055
4056 mlir::Attribute bindNameAttr = builder.getStringAttr(*name);
4057 for (auto crtDeviceTypeAttr : crtDeviceTypes) {
4058 bindNames.push_back(bindNameAttr);
4059 bindNameDeviceTypes.push_back(crtDeviceTypeAttr);
4060 }
4061 }
4062 } else if (const auto *deviceTypeClause =
4063 std::get_if<Fortran::parser::AccClause::DeviceType>(
4064 &clause.u)) {
4065 crtDeviceTypes.clear();
4066 gatherDeviceTypeAttrs(builder, deviceTypeClause, crtDeviceTypes);
4067 }
4068 }
4069
4070 mlir::OpBuilder modBuilder(mod.getBodyRegion());
4071 std::stringstream routineOpName;
4072 routineOpName << accRoutinePrefix.str() << routineCounter++;
4073
4074 for (auto routineOp : mod.getOps<mlir::acc::RoutineOp>()) {
4075 if (routineOp.getFuncName().str().compare(funcName) == 0) {
4076 // If the routine is already specified with the same clauses, just skip
4077 // the operation creation.
4078 if (compareDeviceTypeInfo(routineOp, bindNames, bindNameDeviceTypes,
4079 gangDeviceTypes, gangDimValues,
4080 gangDimDeviceTypes, seqDeviceTypes,
4081 workerDeviceTypes, vectorDeviceTypes) &&
4082 routineOp.getNohost() == hasNohost)
4083 return;
4084 mlir::emitError(loc, "Routine already specified with different clauses");
4085 }
4086 }
4087
4088 modBuilder.create<mlir::acc::RoutineOp>(
4089 loc, routineOpName.str(), funcName,
4090 bindNames.empty() ? nullptr : builder.getArrayAttr(bindNames),
4091 bindNameDeviceTypes.empty() ? nullptr
4092 : builder.getArrayAttr(bindNameDeviceTypes),
4093 workerDeviceTypes.empty() ? nullptr
4094 : builder.getArrayAttr(workerDeviceTypes),
4095 vectorDeviceTypes.empty() ? nullptr
4096 : builder.getArrayAttr(vectorDeviceTypes),
4097 seqDeviceTypes.empty() ? nullptr : builder.getArrayAttr(seqDeviceTypes),
4098 hasNohost, /*implicit=*/false,
4099 gangDeviceTypes.empty() ? nullptr : builder.getArrayAttr(gangDeviceTypes),
4100 gangDimValues.empty() ? nullptr : builder.getArrayAttr(gangDimValues),
4101 gangDimDeviceTypes.empty() ? nullptr
4102 : builder.getArrayAttr(gangDimDeviceTypes));
4103
4104 if (funcOp)
4105 attachRoutineInfo(funcOp, builder.getSymbolRefAttr(routineOpName.str()));
4106 else
4107 // FuncOp is not lowered yet. Keep the information so the routine info
4108 // can be attached later to the funcOp.
4109 accRoutineInfos.push_back(std::make_pair(
4110 funcName, builder.getSymbolRefAttr(routineOpName.str())));
4111 }
4112
4113 void Fortran::lower::finalizeOpenACCRoutineAttachment(
4114 mlir::ModuleOp &mod,
4115 Fortran::lower::AccRoutineInfoMappingList &accRoutineInfos) {
4116 for (auto &mapping : accRoutineInfos) {
4117 mlir::func::FuncOp funcOp =
4118 mod.lookupSymbol<mlir::func::FuncOp>(mapping.first);
4119 if (!funcOp)
4120 mlir::emitWarning(mod.getLoc(),
4121 llvm::Twine("function '") + llvm::Twine(mapping.first) +
4122 llvm::Twine("' in acc routine directive is not "
4123 "found in this translation unit."));
4124 else
4125 attachRoutineInfo(funcOp, mapping.second);
4126 }
4127 accRoutineInfos.clear();
4128 }
4129
4130 static void
4131 genACC(Fortran::lower::AbstractConverter &converter,
4132 Fortran::lower::pft::Evaluation &eval,
4133 const Fortran::parser::OpenACCAtomicConstruct &atomicConstruct) {
4134
4135 mlir::Location loc = converter.genLocation(atomicConstruct.source);
4136 Fortran::common::visit(
4137 Fortran::common::visitors{
4138 [&](const Fortran::parser::AccAtomicRead &atomicRead) {
4139 Fortran::lower::genOmpAccAtomicRead<Fortran::parser::AccAtomicRead,
4140 void>(converter, atomicRead,
4141 loc);
4142 },
4143 [&](const Fortran::parser::AccAtomicWrite &atomicWrite) {
4144 Fortran::lower::genOmpAccAtomicWrite<
4145 Fortran::parser::AccAtomicWrite, void>(converter, atomicWrite,
4146 loc);
4147 },
4148 [&](const Fortran::parser::AccAtomicUpdate &atomicUpdate) {
4149 Fortran::lower::genOmpAccAtomicUpdate<
4150 Fortran::parser::AccAtomicUpdate, void>(converter, atomicUpdate,
4151 loc);
4152 },
4153 [&](const Fortran::parser::AccAtomicCapture &atomicCapture) {
4154 Fortran::lower::genOmpAccAtomicCapture<
4155 Fortran::parser::AccAtomicCapture, void>(converter,
4156 atomicCapture, loc);
4157 },
4158 },
4159 atomicConstruct.u);
4160 }
4161
4162 static void
4163 genACC(Fortran::lower::AbstractConverter &converter,
4164 Fortran::semantics::SemanticsContext &semanticsContext,
4165 const Fortran::parser::OpenACCCacheConstruct &cacheConstruct) {
4166 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
4167 auto loopOp = builder.getRegion().getParentOfType<mlir::acc::LoopOp>();
4168 auto crtPos = builder.saveInsertionPoint();
4169 if (loopOp) {
4170 builder.setInsertionPoint(loopOp);
4171 Fortran::lower::StatementContext stmtCtx;
4172 llvm::SmallVector<mlir::Value> cacheOperands;
4173 const Fortran::parser::AccObjectListWithModifier &listWithModifier =
4174 std::get<Fortran::parser::AccObjectListWithModifier>(cacheConstruct.t);
4175 const auto &accObjectList =
4176 std::get<Fortran::parser::AccObjectList>(listWithModifier.t);
4177 const auto &modifier =
4178 std::get<std::optional<Fortran::parser::AccDataModifier>>(
4179 listWithModifier.t);
4180
4181 mlir::acc::DataClause dataClause = mlir::acc::DataClause::acc_cache;
4182 if (modifier &&
4183 (*modifier).v == Fortran::parser::AccDataModifier::Modifier::ReadOnly)
4184 dataClause = mlir::acc::DataClause::acc_cache_readonly;
4185 genDataOperandOperations<mlir::acc::CacheOp>(
4186 accObjectList, converter, semanticsContext, stmtCtx, cacheOperands,
4187 dataClause,
4188 /*structured=*/true, /*implicit=*/false,
4189 /*async=*/{}, /*asyncDeviceTypes=*/{}, /*asyncOnlyDeviceTypes=*/{},
4190 /*setDeclareAttr*/ false);
4191 loopOp.getCacheOperandsMutable().append(cacheOperands);
4192 } else {
4193 llvm::report_fatal_error(
4194 "could not find loop to attach OpenACC cache information.");
4195 }
4196 builder.restoreInsertionPoint(crtPos);
4197 }
4198
4199 mlir::Value Fortran::lower::genOpenACCConstruct(
4200 Fortran::lower::AbstractConverter &converter,
4201 Fortran::semantics::SemanticsContext &semanticsContext,
4202 Fortran::lower::pft::Evaluation &eval,
4203 const Fortran::parser::OpenACCConstruct &accConstruct) {
4204
4205 mlir::Value exitCond;
4206 Fortran::common::visit(
4207 common::visitors{
4208 [&](const Fortran::parser::OpenACCBlockConstruct &blockConstruct) {
4209 genACC(converter, semanticsContext, eval, blockConstruct);
4210 },
4211 [&](const Fortran::parser::OpenACCCombinedConstruct
4212 &combinedConstruct) {
4213 genACC(converter, semanticsContext, eval, combinedConstruct);
4214 },
4215 [&](const Fortran::parser::OpenACCLoopConstruct &loopConstruct) {
4216 exitCond = genACC(converter, semanticsContext, eval, loopConstruct);
4217 },
4218 [&](const Fortran::parser::OpenACCStandaloneConstruct
4219 &standaloneConstruct) {
4220 genACC(converter, semanticsContext, standaloneConstruct);
4221 },
4222 [&](const Fortran::parser::OpenACCCacheConstruct &cacheConstruct) {
4223 genACC(converter, semanticsContext, cacheConstruct);
4224 },
4225 [&](const Fortran::parser::OpenACCWaitConstruct &waitConstruct) {
4226 genACC(converter, waitConstruct);
4227 },
4228 [&](const Fortran::parser::OpenACCAtomicConstruct &atomicConstruct) {
4229 genACC(converter, eval, atomicConstruct);
4230 },
4231 [&](const Fortran::parser::OpenACCEndConstruct &) {
4232 // No op
4233 },
4234 },
4235 accConstruct.u);
4236 return exitCond;
4237 }
4238
4239 void Fortran::lower::genOpenACCDeclarativeConstruct(
4240 Fortran::lower::AbstractConverter &converter,
4241 Fortran::semantics::SemanticsContext &semanticsContext,
4242 Fortran::lower::StatementContext &openAccCtx,
4243 const Fortran::parser::OpenACCDeclarativeConstruct &accDeclConstruct,
4244 Fortran::lower::AccRoutineInfoMappingList &accRoutineInfos) {
4245
4246 Fortran::common::visit(
4247 common::visitors{
4248 [&](const Fortran::parser::OpenACCStandaloneDeclarativeConstruct
4249 &standaloneDeclarativeConstruct) {
4250 genACC(converter, semanticsContext, openAccCtx,
4251 standaloneDeclarativeConstruct);
4252 },
4253 [&](const Fortran::parser::OpenACCRoutineConstruct
4254 &routineConstruct) {
4255 fir::FirOpBuilder &builder = converter.getFirOpBuilder();
4256 mlir::ModuleOp mod = builder.getModule();
4257 Fortran::lower::genOpenACCRoutineConstruct(
4258 converter, semanticsContext, mod, routineConstruct,
4259 accRoutineInfos);
4260 },
4261 },
4262 accDeclConstruct.u);
4263 }
4264
4265 void Fortran::lower::attachDeclarePostAllocAction(
4266 AbstractConverter &converter, fir::FirOpBuilder &builder,
4267 const Fortran::semantics::Symbol &sym) {
4268 std::stringstream fctName;
4269 fctName << converter.mangleName(sym) << declarePostAllocSuffix.str();
4270 mlir::Operation &op = builder.getInsertionBlock()->back();
4271
4272 if (op.hasAttr(mlir::acc::getDeclareActionAttrName())) {
4273 auto attr = op.getAttrOfType<mlir::acc::DeclareActionAttr>(
4274 mlir::acc::getDeclareActionAttrName());
4275 op.setAttr(mlir::acc::getDeclareActionAttrName(),
4276 mlir::acc::DeclareActionAttr::get(
4277 builder.getContext(), attr.getPreAlloc(),
4278 /*postAlloc=*/builder.getSymbolRefAttr(fctName.str()),
4279 attr.getPreDealloc(), attr.getPostDealloc()));
4280 } else {
4281 op.setAttr(mlir::acc::getDeclareActionAttrName(),
4282 mlir::acc::DeclareActionAttr::get(
4283 builder.getContext(),
4284 /*preAlloc=*/{},
4285 /*postAlloc=*/builder.getSymbolRefAttr(fctName.str()),
4286 /*preDealloc=*/{}, /*postDealloc=*/{}));
4287 }
4288 }
4289
4290 void Fortran::lower::attachDeclarePreDeallocAction(
4291 AbstractConverter &converter, fir::FirOpBuilder &builder,
4292 mlir::Value beginOpValue, const Fortran::semantics::Symbol &sym) {
4293 if (!sym.test(Fortran::semantics::Symbol::Flag::AccCreate) &&
4294 !sym.test(Fortran::semantics::Symbol::Flag::AccCopyIn) &&
4295 !sym.test(Fortran::semantics::Symbol::Flag::AccCopyInReadOnly) &&
4296 !sym.test(Fortran::semantics::Symbol::Flag::AccCopy) &&
4297 !sym.test(Fortran::semantics::Symbol::Flag::AccCopyOut) &&
4298 !sym.test(Fortran::semantics::Symbol::Flag::AccDeviceResident))
4299 return;
4300
4301 std::stringstream fctName;
4302 fctName << converter.mangleName(sym) << declarePreDeallocSuffix.str();
4303
4304 auto *op = beginOpValue.getDefiningOp();
4305 if (op->hasAttr(mlir::acc::getDeclareActionAttrName())) {
4306 auto attr = op->getAttrOfType<mlir::acc::DeclareActionAttr>(
4307 mlir::acc::getDeclareActionAttrName());
4308 op->setAttr(mlir::acc::getDeclareActionAttrName(),
4309 mlir::acc::DeclareActionAttr::get(
4310 builder.getContext(), attr.getPreAlloc(),
4311 attr.getPostAlloc(),
4312 /*preDealloc=*/builder.getSymbolRefAttr(fctName.str()),
4313 attr.getPostDealloc()));
4314 } else {
4315 op->setAttr(mlir::acc::getDeclareActionAttrName(),
4316 mlir::acc::DeclareActionAttr::get(
4317 builder.getContext(),
4318 /*preAlloc=*/{}, /*postAlloc=*/{},
4319 /*preDealloc=*/builder.getSymbolRefAttr(fctName.str()),
4320 /*postDealloc=*/{}));
4321 }
4322 }
4323
4324 void Fortran::lower::attachDeclarePostDeallocAction(
4325 AbstractConverter &converter, fir::FirOpBuilder &builder,
4326 const Fortran::semantics::Symbol &sym) {
4327 if (!sym.test(Fortran::semantics::Symbol::Flag::AccCreate) &&
4328 !sym.test(Fortran::semantics::Symbol::Flag::AccCopyIn) &&
4329 !sym.test(Fortran::semantics::Symbol::Flag::AccCopyInReadOnly) &&
4330 !sym.test(Fortran::semantics::Symbol::Flag::AccCopy) &&
4331 !sym.test(Fortran::semantics::Symbol::Flag::AccCopyOut) &&
4332 !sym.test(Fortran::semantics::Symbol::Flag::AccDeviceResident))
4333 return;
4334
4335 std::stringstream fctName;
4336 fctName << converter.mangleName(sym) << declarePostDeallocSuffix.str();
4337 mlir::Operation *op = &builder.getInsertionBlock()->back();
4338 if (auto resOp = mlir::dyn_cast<fir::ResultOp>(*op)) {
4339 assert(resOp.getOperands().size() == 0 &&
4340 "expect only fir.result op with no operand");
4341 op = op->getPrevNode();
4342 }
4343 assert(op && "expect operation to attach the post deallocation action");
4344 if (op->hasAttr(mlir::acc::getDeclareActionAttrName())) {
4345 auto attr = op->getAttrOfType<mlir::acc::DeclareActionAttr>(
4346 mlir::acc::getDeclareActionAttrName());
4347 op->setAttr(mlir::acc::getDeclareActionAttrName(),
4348 mlir::acc::DeclareActionAttr::get(
4349 builder.getContext(), attr.getPreAlloc(),
4350 attr.getPostAlloc(), attr.getPreDealloc(),
4351 /*postDealloc=*/builder.getSymbolRefAttr(fctName.str())));
4352 } else {
4353 op->setAttr(mlir::acc::getDeclareActionAttrName(),
4354 mlir::acc::DeclareActionAttr::get(
4355 builder.getContext(),
4356 /*preAlloc=*/{}, /*postAlloc=*/{}, /*preDealloc=*/{},
4357 /*postDealloc=*/builder.getSymbolRefAttr(fctName.str())));
4358 }
4359 }
4360
4361 void Fortran::lower::genOpenACCTerminator(fir::FirOpBuilder &builder,
4362 mlir::Operation *op,
4363 mlir::Location loc) {
4364 if (mlir::isa<mlir::acc::ParallelOp, mlir::acc::LoopOp>(op))
4365 builder.create<mlir::acc::YieldOp>(loc);
4366 else
4367 builder.create<mlir::acc::TerminatorOp>(loc);
4368 }
4369
4370 bool Fortran::lower::isInOpenACCLoop(fir::FirOpBuilder &builder) {
4371 if (builder.getBlock()->getParent()->getParentOfType<mlir::acc::LoopOp>())
4372 return true;
4373 return false;
4374 }
4375
4376 void Fortran::lower::setInsertionPointAfterOpenACCLoopIfInside(
4377 fir::FirOpBuilder &builder) {
4378 if (auto loopOp =
4379 builder.getBlock()->getParent()->getParentOfType<mlir::acc::LoopOp>())
4380 builder.setInsertionPointAfter(loopOp);
4381 }
4382
4383 void Fortran::lower::genEarlyReturnInOpenACCLoop(fir::FirOpBuilder &builder,
4384 mlir::Location loc) {
4385 mlir::Value yieldValue =
4386 builder.createIntegerConstant(loc, builder.getI1Type(), 1);
4387 builder.create<mlir::acc::YieldOp>(loc, yieldValue);
4388 }
4389
4390 int64_t Fortran::lower::getCollapseValue(
4391 const Fortran::parser::AccClauseList &clauseList) {
4392 for (const Fortran::parser::AccClause &clause : clauseList.v) {
4393 if (const auto *collapseClause =
4394 std::get_if<Fortran::parser::AccClause::Collapse>(&clause.u)) {
4395 const parser::AccCollapseArg &arg = collapseClause->v;
4396 const auto &collapseValue{std::get<parser::ScalarIntConstantExpr>(arg.t)};
4397 return *Fortran::semantics::GetIntValue(collapseValue);
4398 }
4399 }
4400 return 1;
4401 }