clang 23.0.0git
CIRGenStmtOpenACC.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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// Emit OpenACC Stmt nodes as CIR code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CIRGenBuilder.h"
14#include "CIRGenFunction.h"
15#include "mlir/Dialect/OpenACC/OpenACC.h"
18
19using namespace clang;
20using namespace clang::CIRGen;
21using namespace cir;
22using namespace mlir::acc;
23
24template <typename Op, typename TermOp>
25mlir::LogicalResult CIRGenFunction::emitOpenACCOpAssociatedStmt(
26 mlir::Location start, mlir::Location end, OpenACCDirectiveKind dirKind,
27 llvm::ArrayRef<const OpenACCClause *> clauses, const Stmt *associatedStmt) {
28 mlir::LogicalResult res = mlir::success();
29
30 llvm::SmallVector<mlir::Type> retTy;
31 llvm::SmallVector<mlir::Value> operands;
32 auto op = Op::create(builder, start, retTy, operands);
33
34 emitOpenACCClauses(op, dirKind, clauses);
35
36 {
37 mlir::Block &block = op.getRegion().emplaceBlock();
38 mlir::OpBuilder::InsertionGuard guardCase(builder);
39 builder.setInsertionPointToEnd(&block);
40
41 LexicalScope ls{*this, start, builder.getInsertionBlock()};
42 res = emitStmt(associatedStmt, /*useCurrentScope=*/true);
43
44 TermOp::create(builder, end);
45 }
46 return res;
47}
48
49namespace {
50template <typename Op> struct CombinedType;
51template <> struct CombinedType<ParallelOp> {
52 static constexpr mlir::acc::CombinedConstructsType value =
53 mlir::acc::CombinedConstructsType::ParallelLoop;
54};
55template <> struct CombinedType<SerialOp> {
56 static constexpr mlir::acc::CombinedConstructsType value =
57 mlir::acc::CombinedConstructsType::SerialLoop;
58};
59template <> struct CombinedType<KernelsOp> {
60 static constexpr mlir::acc::CombinedConstructsType value =
61 mlir::acc::CombinedConstructsType::KernelsLoop;
62};
63} // namespace
64
65template <typename Op, typename TermOp>
66mlir::LogicalResult CIRGenFunction::emitOpenACCOpCombinedConstruct(
67 mlir::Location start, mlir::Location end, OpenACCDirectiveKind dirKind,
68 llvm::ArrayRef<const OpenACCClause *> clauses, const Stmt *loopStmt) {
69 mlir::LogicalResult res = mlir::success();
70
71 llvm::SmallVector<mlir::Type> retTy;
72 llvm::SmallVector<mlir::Value> operands;
73
74 auto computeOp = Op::create(builder, start, retTy, operands);
75 computeOp.setCombinedAttr(builder.getUnitAttr());
76 mlir::acc::LoopOp loopOp;
77
78 // First, emit the bodies of both operations, with the loop inside the body of
79 // the combined construct.
80 {
81 mlir::Block &block = computeOp.getRegion().emplaceBlock();
82 mlir::OpBuilder::InsertionGuard guardCase(builder);
83 builder.setInsertionPointToEnd(&block);
84
85 LexicalScope ls{*this, start, builder.getInsertionBlock()};
86 auto loopOp = LoopOp::create(builder, start, retTy, operands);
87 loopOp.setCombinedAttr(mlir::acc::CombinedConstructsTypeAttr::get(
88 builder.getContext(), CombinedType<Op>::value));
89
90 {
91 mlir::Block &innerBlock = loopOp.getRegion().emplaceBlock();
92 mlir::OpBuilder::InsertionGuard guardCase(builder);
93 builder.setInsertionPointToEnd(&innerBlock);
94
95 LexicalScope ls{*this, start, builder.getInsertionBlock()};
96 ActiveOpenACCLoopRAII activeLoop{*this, &loopOp};
97
98 res = emitStmt(loopStmt, /*useCurrentScope=*/true);
99
100 mlir::acc::YieldOp::create(builder, end);
101 }
102
103 emitOpenACCClauses(computeOp, loopOp, dirKind, clauses);
104
105 updateLoopOpParallelism(loopOp, /*isOrphan=*/false, dirKind);
106
107 TermOp::create(builder, end);
108 }
109
110 return res;
111}
112
113template <typename Op>
114Op CIRGenFunction::emitOpenACCOp(
115 mlir::Location start, OpenACCDirectiveKind dirKind,
116 llvm::ArrayRef<const OpenACCClause *> clauses) {
117 llvm::SmallVector<mlir::Type> retTy;
118 llvm::SmallVector<mlir::Value> operands;
119 auto op = Op::create(builder, start, retTy, operands);
120
121 emitOpenACCClauses(op, dirKind, clauses);
122 return op;
123}
124
125mlir::LogicalResult
127 mlir::Location start = getLoc(s.getSourceRange().getBegin());
128 mlir::Location end = getLoc(s.getSourceRange().getEnd());
129
130 switch (s.getDirectiveKind()) {
132 return emitOpenACCOpAssociatedStmt<ParallelOp, mlir::acc::YieldOp>(
133 start, end, s.getDirectiveKind(), s.clauses(), s.getStructuredBlock());
135 return emitOpenACCOpAssociatedStmt<SerialOp, mlir::acc::YieldOp>(
136 start, end, s.getDirectiveKind(), s.clauses(), s.getStructuredBlock());
138 return emitOpenACCOpAssociatedStmt<KernelsOp, mlir::acc::TerminatorOp>(
139 start, end, s.getDirectiveKind(), s.clauses(), s.getStructuredBlock());
140 default:
141 llvm_unreachable("invalid compute construct kind");
142 }
143}
144
145mlir::LogicalResult
147 mlir::Location start = getLoc(s.getSourceRange().getBegin());
148 mlir::Location end = getLoc(s.getSourceRange().getEnd());
149
150 return emitOpenACCOpAssociatedStmt<DataOp, mlir::acc::TerminatorOp>(
151 start, end, s.getDirectiveKind(), s.clauses(), s.getStructuredBlock());
152}
153
154mlir::LogicalResult
156 mlir::Location start = getLoc(s.getSourceRange().getBegin());
157 emitOpenACCOp<InitOp>(start, s.getDirectiveKind(), s.clauses());
158 return mlir::success();
159}
160
161mlir::LogicalResult
163 mlir::Location start = getLoc(s.getSourceRange().getBegin());
164 emitOpenACCOp<SetOp>(start, s.getDirectiveKind(), s.clauses());
165 return mlir::success();
166}
167
169 const OpenACCShutdownConstruct &s) {
170 mlir::Location start = getLoc(s.getSourceRange().getBegin());
171 emitOpenACCOp<ShutdownOp>(start, s.getDirectiveKind(), s.clauses());
172 return mlir::success();
173}
174
175mlir::LogicalResult
177 mlir::Location start = getLoc(s.getSourceRange().getBegin());
178 auto waitOp = emitOpenACCOp<WaitOp>(start, s.getDirectiveKind(), s.clauses());
179
180 auto createIntExpr = [this](const Expr *intExpr) {
181 mlir::Value expr = emitScalarExpr(intExpr);
182 mlir::Location exprLoc = cgm.getLoc(intExpr->getBeginLoc());
183
184 mlir::IntegerType targetType = mlir::IntegerType::get(
185 &getMLIRContext(), getContext().getIntWidth(intExpr->getType()),
186 intExpr->getType()->isSignedIntegerOrEnumerationType()
187 ? mlir::IntegerType::SignednessSemantics::Signed
188 : mlir::IntegerType::SignednessSemantics::Unsigned);
189
190 return builder.createBuiltinIntCast(exprLoc, expr, targetType);
191 };
192
193 // Emit the correct 'wait' clauses.
194 {
195 mlir::OpBuilder::InsertionGuard guardCase(builder);
196 builder.setInsertionPoint(waitOp);
197
198 if (s.hasDevNumExpr())
199 waitOp.getWaitDevnumMutable().append(createIntExpr(s.getDevNumExpr()));
200
201 for (Expr *QueueExpr : s.getQueueIdExprs())
202 waitOp.getWaitOperandsMutable().append(createIntExpr(QueueExpr));
203 }
204
205 return mlir::success();
206}
207
209 const OpenACCCombinedConstruct &s) {
210 mlir::Location start = getLoc(s.getSourceRange().getBegin());
211 mlir::Location end = getLoc(s.getSourceRange().getEnd());
212
213 switch (s.getDirectiveKind()) {
215 return emitOpenACCOpCombinedConstruct<ParallelOp, mlir::acc::YieldOp>(
216 start, end, s.getDirectiveKind(), s.clauses(), s.getLoop());
218 return emitOpenACCOpCombinedConstruct<SerialOp, mlir::acc::YieldOp>(
219 start, end, s.getDirectiveKind(), s.clauses(), s.getLoop());
221 return emitOpenACCOpCombinedConstruct<KernelsOp, mlir::acc::TerminatorOp>(
222 start, end, s.getDirectiveKind(), s.clauses(), s.getLoop());
223 default:
224 llvm_unreachable("invalid compute construct kind");
225 }
226}
227
229 const OpenACCHostDataConstruct &s) {
230 mlir::Location start = getLoc(s.getSourceRange().getBegin());
231 mlir::Location end = getLoc(s.getSourceRange().getEnd());
232
233 return emitOpenACCOpAssociatedStmt<HostDataOp, mlir::acc::TerminatorOp>(
234 start, end, s.getDirectiveKind(), s.clauses(), s.getStructuredBlock());
235}
236
238 const OpenACCEnterDataConstruct &s) {
239 mlir::Location start = getLoc(s.getSourceRange().getBegin());
240 emitOpenACCOp<EnterDataOp>(start, s.getDirectiveKind(), s.clauses());
241 return mlir::success();
242}
243
245 const OpenACCExitDataConstruct &s) {
246 mlir::Location start = getLoc(s.getSourceRange().getBegin());
247 emitOpenACCOp<ExitDataOp>(start, s.getDirectiveKind(), s.clauses());
248 return mlir::success();
249}
250
251mlir::LogicalResult
253 mlir::Location start = getLoc(s.getSourceRange().getBegin());
254 emitOpenACCOp<UpdateOp>(start, s.getDirectiveKind(), s.clauses());
255 return mlir::success();
256}
257
258mlir::LogicalResult
260 // The 'cache' directive 'may' be at the top of a loop by standard, but
261 // doesn't have to be. Additionally, there is nothing that requires this be a
262 // loop affected by an OpenACC pragma. Sema doesn't do any level of
263 // enforcement here, since it isn't particularly valuable to do so thanks to
264 // that. Instead, we treat cache as a 'noop' if there is no acc.loop to apply
265 // it to.
266 if (!activeLoopOp)
267 return mlir::success();
268
269 mlir::acc::LoopOp loopOp = *activeLoopOp;
270
271 mlir::OpBuilder::InsertionGuard guard(builder);
272 builder.setInsertionPoint(loopOp);
273
274 for (const Expr *var : s.getVarList()) {
277
278 auto cacheOp = CacheOp::create(builder, opInfo.beginLoc, opInfo.varValue,
279 /*structured=*/false, /*implicit=*/false,
280 opInfo.name, opInfo.bounds);
281
282 loopOp.getCacheOperandsMutable().append(cacheOp.getResult());
283 }
284
285 return mlir::success();
286}
287
288const VarDecl *getLValueDecl(const Expr *e) {
289 // We are going to assume that after stripping implicit casts, that the LValue
290 // is just a DRE around the var-decl.
291
292 e = e->IgnoreImpCasts();
293
294 const auto *dre = cast<DeclRefExpr>(e);
295 return cast<VarDecl>(dre->getDecl());
296}
297
298static mlir::acc::AtomicReadOp
300 mlir::Location start,
302 // Atomic 'read' only permits 'v = x', where v and x are both scalar L
303 // values. The getAssociatedStmtInfo strips off implicit casts, which
304 // includes implicit conversions and L-to-R-Value conversions, so we can
305 // just emit it as an L value. The Flang implementation has no problem with
306 // different types, so it appears that the dialect can handle the
307 // conversions.
308 mlir::Value v = cgf.emitLValue(inf.V).getPointer();
309 mlir::Value x = cgf.emitLValue(inf.X).getPointer();
310 mlir::Type resTy = cgf.convertType(inf.V->getType());
311 return mlir::acc::AtomicReadOp::create(builder, start, x, v, resTy,
312 /*ifCond=*/{});
313}
314
315static mlir::acc::AtomicWriteOp
317 mlir::Location start,
319 mlir::Value x = cgf.emitLValue(inf.X).getPointer();
320 mlir::Value expr = cgf.emitAnyExpr(inf.RefExpr).getValue();
321 return mlir::acc::AtomicWriteOp::create(builder, start, x, expr,
322 /*ifCond=*/{});
323}
324
325static std::pair<mlir::LogicalResult, mlir::acc::AtomicUpdateOp>
327 mlir::Location start, mlir::Location end,
329 mlir::Value x = cgf.emitLValue(inf.X).getPointer();
330 auto op = mlir::acc::AtomicUpdateOp::create(builder, start, x, /*ifCond=*/{});
331
332 mlir::LogicalResult res = mlir::success();
333 {
334 mlir::OpBuilder::InsertionGuard guardCase(builder);
335 mlir::Type argTy = cast<cir::PointerType>(x.getType()).getPointee();
336 std::array<mlir::Type, 1> recipeType{argTy};
337 std::array<mlir::Location, 1> recipeLoc{start};
338 auto *recipeBlock = builder.createBlock(
339 &op.getRegion(), op.getRegion().end(), recipeType, recipeLoc);
340 builder.setInsertionPointToEnd(recipeBlock);
341 // Since we have an initial value that we know is a scalar type, we can
342 // just emit the entire statement here after sneaking-in our 'alloca' in
343 // the right place, then loading out of it. Flang does a lot less work
344 // (probably does its own emitting!), but we have more complicated AST
345 // nodes to worry about, so we can just count on opt to remove the extra
346 // alloca/load/store set.
347 auto alloca = cir::AllocaOp::create(
348 builder, start, x.getType(), "x_var",
349 cgf.cgm.getSize(
350 cgf.getContext().getTypeAlignInChars(inf.X->getType())));
351
352 alloca.setInitAttr(builder.getUnitAttr());
353 builder.CIRBaseBuilderTy::createStore(start, recipeBlock->getArgument(0),
354 alloca);
355
356 const VarDecl *xval = getLValueDecl(inf.X);
357 CIRGenFunction::DeclMapRevertingRAII declMapRAII{cgf, xval};
359 xval, Address{alloca, argTy, cgf.getContext().getDeclAlign(xval)});
360
361 res = cgf.emitStmt(inf.WholeExpr, /*useCurrentScope=*/true);
362
363 auto load = cir::LoadOp::create(builder, start, {alloca});
364 mlir::acc::YieldOp::create(builder, end, {load});
365 }
366
367 return {res, op};
368}
369
370mlir::LogicalResult
372 // While Atomic is an 'associated statement' construct, it 'steals' the
373 // expression it is associated with rather than emitting it inside of it. So
374 // it has custom emit logic.
375 mlir::Location start = getLoc(s.getSourceRange().getBegin());
376 mlir::Location end = getLoc(s.getSourceRange().getEnd());
378
379 switch (s.getAtomicKind()) {
382 mlir::acc::AtomicReadOp op =
383 emitAtomicRead(*this, builder, start, inf.First);
384 emitOpenACCClauses(op, s.getDirectiveKind(), s.clauses());
385 return mlir::success();
386 }
389 auto op = emitAtomicWrite(*this, builder, start, inf.First);
390 emitOpenACCClauses(op, s.getDirectiveKind(), s.clauses());
391 return mlir::success();
392 }
396 auto [res, op] = emitAtomicUpdate(*this, builder, start, end, inf.First);
397 emitOpenACCClauses(op, s.getDirectiveKind(), s.clauses());
398 return res;
399 }
401 // Atomic-capture is made up of two statements, either an update = read,
402 // read + update, or read + write. As a result, the IR represents the
403 // capture region as having those two 'inside' of it.
404 auto op = mlir::acc::AtomicCaptureOp::create(builder, start, /*ifCond=*/{});
405 emitOpenACCClauses(op, s.getDirectiveKind(), s.clauses());
406 mlir::LogicalResult res = mlir::success();
407 {
408 mlir::OpBuilder::InsertionGuard guardCase(builder);
409
410 mlir::Block *block =
411 builder.createBlock(&op.getRegion(), op.getRegion().end(), {}, {});
412
413 builder.setInsertionPointToStart(block);
414
415 auto terminator = mlir::acc::TerminatorOp::create(builder, end);
416
417 // The AtomicCaptureOp only permits the two acc.atomic.* operations inside
418 // of it, so all other parts of the expression need to be emitted before
419 // the AtomicCaptureOp, then moved into place.
420 builder.setInsertionPoint(op);
421
422 switch (inf.Form) {
423 default:
424 llvm_unreachable("invalid form for Capture");
426 mlir::acc::AtomicReadOp first =
427 emitAtomicRead(*this, builder, start, inf.First);
428 mlir::acc::AtomicWriteOp second =
429 emitAtomicWrite(*this, builder, start, inf.Second);
430
431 first->moveBefore(terminator);
432 second->moveBefore(terminator);
433 break;
434 }
436 mlir::acc::AtomicReadOp first =
437 emitAtomicRead(*this, builder, start, inf.First);
438 auto [this_res, second] =
439 emitAtomicUpdate(*this, builder, start, end, inf.Second);
440 res = this_res;
441
442 first->moveBefore(terminator);
443 second->moveBefore(terminator);
444 break;
445 }
447 auto [this_res, first] =
448 emitAtomicUpdate(*this, builder, start, end, inf.First);
449 res = this_res;
450 mlir::acc::AtomicReadOp second =
451 emitAtomicRead(*this, builder, start, inf.Second);
452
453 first->moveBefore(terminator);
454 second->moveBefore(terminator);
455 break;
456 }
457 }
458 }
459 return res;
460 }
461 }
462
463 llvm_unreachable("unknown OpenACC atomic kind");
464}
static mlir::acc::AtomicReadOp emitAtomicRead(CIRGenFunction &cgf, CIRGenBuilderTy &builder, mlir::Location start, const OpenACCAtomicConstruct::SingleStmtInfo &inf)
static std::pair< mlir::LogicalResult, mlir::acc::AtomicUpdateOp > emitAtomicUpdate(CIRGenFunction &cgf, CIRGenBuilderTy &builder, mlir::Location start, mlir::Location end, const OpenACCAtomicConstruct::SingleStmtInfo &inf)
static mlir::acc::AtomicWriteOp emitAtomicWrite(CIRGenFunction &cgf, CIRGenBuilderTy &builder, mlir::Location start, const OpenACCAtomicConstruct::SingleStmtInfo &inf)
const VarDecl * getLValueDecl(const Expr *e)
This file defines OpenACC AST classes for statement-level contructs.
const StmtInfo getAssociatedStmtInfo() const
OpenACCAtomicKind getAtomicKind() const
ArrayRef< Expr * > getVarList() const
Stmt * getStructuredBlock()
bool hasDevNumExpr() const
ArrayRef< Expr * > getQueueIdExprs() const
Expr * getDevNumExpr() const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
mlir::Type convertType(clang::QualType t)
mlir::LogicalResult emitOpenACCDataConstruct(const OpenACCDataConstruct &s)
mlir::LogicalResult emitOpenACCCombinedConstruct(const OpenACCCombinedConstruct &s)
mlir::LogicalResult emitOpenACCWaitConstruct(const OpenACCWaitConstruct &s)
mlir::LogicalResult emitOpenACCUpdateConstruct(const OpenACCUpdateConstruct &s)
mlir::LogicalResult emitOpenACCCacheConstruct(const OpenACCCacheConstruct &s)
void replaceAddrOfLocalVar(const clang::VarDecl *vd, Address addr)
LValue emitLValue(const clang::Expr *e)
Emit code to compute a designator that specifies the location of the expression.
mlir::Location getLoc(clang::SourceLocation srcLoc)
Helpers to convert Clang's SourceLocation to a MLIR Location.
mlir::LogicalResult emitOpenACCInitConstruct(const OpenACCInitConstruct &s)
mlir::LogicalResult emitOpenACCSetConstruct(const OpenACCSetConstruct &s)
OpenACCDataOperandInfo getOpenACCDataOperandInfo(const Expr *e)
mlir::LogicalResult emitOpenACCComputeConstruct(const OpenACCComputeConstruct &s)
mlir::LogicalResult emitOpenACCShutdownConstruct(const OpenACCShutdownConstruct &s)
mlir::LogicalResult emitOpenACCHostDataConstruct(const OpenACCHostDataConstruct &s)
mlir::Value emitScalarExpr(const clang::Expr *e, bool ignoreResultAssign=false)
Emit the computation of the specified expression of scalar type.
mlir::MLIRContext & getMLIRContext()
mlir::LogicalResult emitOpenACCEnterDataConstruct(const OpenACCEnterDataConstruct &s)
RValue emitAnyExpr(const clang::Expr *e, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
Emit code to compute the specified expression which can have any type.
clang::ASTContext & getContext() const
mlir::LogicalResult emitStmt(const clang::Stmt *s, bool useCurrentScope, llvm::ArrayRef< const Attr * > attrs={})
mlir::LogicalResult emitOpenACCExitDataConstruct(const OpenACCExitDataConstruct &s)
mlir::LogicalResult emitOpenACCAtomicConstruct(const OpenACCAtomicConstruct &s)
mlir::IntegerAttr getSize(CharUnits size)
mlir::Value getPointer() const
mlir::Value getValue() const
Return the value of this scalar value.
Definition CIRGenValue.h:57
This represents one expression.
Definition Expr.h:112
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3079
QualType getType() const
Definition Expr.h:144
Stmt - This represents one statement.
Definition Stmt.h:86
Represents a variable declaration or definition.
Definition Decl.h:932
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
The JSON file list parser is used to communicate input to InstallAPI.
OpenACCDirectiveKind
OpenACCComputeConstruct(OpenACCDirectiveKind K, SourceLocation Start, SourceLocation DirectiveLoc, SourceLocation End, ArrayRef< const OpenACCClause * > Clauses, Stmt *StructuredBlock)
U cast(CodeGen::Address addr)
Definition Address.h:327
enum OpenACCAtomicConstruct::StmtInfo::StmtForm Form
Represents a scope, including function bodies, compound statements, and the substatements of if/while...