clang 22.0.0git
CIRGenCoroutine.cpp
Go to the documentation of this file.
1//===----- CGCoroutine.cpp - Emit CIR Code for C++ coroutines -------------===//
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// This contains code dealing with C++ code generation of coroutines.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CIRGenFunction.h"
14#include "mlir/Support/LLVM.h"
15#include "clang/AST/StmtCXX.h"
20
21using namespace clang;
22using namespace clang::CIRGen;
23
25 // What is the current await expression kind and how many
26 // await/yield expressions were encountered so far.
27 // These are used to generate pretty labels for await expressions in LLVM IR.
28 cir::AwaitKind currentAwaitKind = cir::AwaitKind::Init;
29 // Stores the __builtin_coro_id emitted in the function so that we can supply
30 // it as the first argument to other builtins.
31 cir::CallOp coroId = nullptr;
32
33 // Stores the result of __builtin_coro_begin call.
34 mlir::Value coroBegin = nullptr;
35
36 // The promise type's 'unhandled_exception' handler, if it defines one.
38};
39
40// Defining these here allows to keep CGCoroData private to this file.
43
44namespace {
45// FIXME: both GetParamRef and ParamReferenceReplacerRAII are good template
46// candidates to be shared among LLVM / CIR codegen.
47
48// Hunts for the parameter reference in the parameter copy/move declaration.
49struct GetParamRef : public StmtVisitor<GetParamRef> {
50public:
51 DeclRefExpr *expr = nullptr;
52 GetParamRef() {}
53 void VisitDeclRefExpr(DeclRefExpr *e) {
54 assert(expr == nullptr && "multilple declref in param move");
55 expr = e;
56 }
57 void VisitStmt(Stmt *s) {
58 for (Stmt *c : s->children()) {
59 if (c)
60 Visit(c);
61 }
62 }
63};
64
65// This class replaces references to parameters to their copies by changing
66// the addresses in CGF.LocalDeclMap and restoring back the original values in
67// its destructor.
68struct ParamReferenceReplacerRAII {
69 CIRGenFunction::DeclMapTy savedLocals;
70 CIRGenFunction::DeclMapTy &localDeclMap;
71
72 ParamReferenceReplacerRAII(CIRGenFunction::DeclMapTy &localDeclMap)
73 : localDeclMap(localDeclMap) {}
74
75 void addCopy(const DeclStmt *pm) {
76 // Figure out what param it refers to.
77
78 assert(pm->isSingleDecl());
79 const VarDecl *vd = static_cast<const VarDecl *>(pm->getSingleDecl());
80 const Expr *initExpr = vd->getInit();
81 GetParamRef visitor;
82 visitor.Visit(const_cast<Expr *>(initExpr));
83 assert(visitor.expr);
84 DeclRefExpr *dreOrig = visitor.expr;
85 auto *pd = dreOrig->getDecl();
86
87 auto it = localDeclMap.find(pd);
88 assert(it != localDeclMap.end() && "parameter is not found");
89 savedLocals.insert({pd, it->second});
90
91 auto copyIt = localDeclMap.find(vd);
92 assert(copyIt != localDeclMap.end() && "parameter copy is not found");
93 it->second = copyIt->getSecond();
94 }
95
96 ~ParamReferenceReplacerRAII() {
97 for (auto &&savedLocal : savedLocals) {
98 localDeclMap.insert({savedLocal.first, savedLocal.second});
99 }
100 }
101};
102} // namespace
103
105 if (curCoro.data && curCoro.data->coroBegin) {
106 return RValue::get(curCoro.data->coroBegin);
107 }
108 cgm.errorNYI("NYI");
109 return RValue();
110}
111
114 cir::CallOp coroId) {
115 assert(!curCoro.data && "EmitCoroutineBodyStatement called twice?");
116
117 curCoro.data = std::make_unique<CGCoroData>();
118 curCoro.data->coroId = coroId;
119}
120
121cir::CallOp CIRGenFunction::emitCoroIDBuiltinCall(mlir::Location loc,
122 mlir::Value nullPtr) {
123 cir::IntType int32Ty = builder.getUInt32Ty();
124
125 const TargetInfo &ti = cgm.getASTContext().getTargetInfo();
126 unsigned newAlign = ti.getNewAlign() / ti.getCharWidth();
127
128 mlir::Operation *builtin = cgm.getGlobalValue(cgm.builtinCoroId);
129
130 cir::FuncOp fnOp;
131 if (!builtin) {
132 fnOp = cgm.createCIRBuiltinFunction(
133 loc, cgm.builtinCoroId,
134 cir::FuncType::get({int32Ty, voidPtrTy, voidPtrTy, voidPtrTy}, int32Ty),
135 /*FD=*/nullptr);
136 assert(fnOp && "should always succeed");
137 } else {
138 fnOp = cast<cir::FuncOp>(builtin);
139 }
140
141 return builder.createCallOp(loc, fnOp,
142 mlir::ValueRange{builder.getUInt32(newAlign, loc),
143 nullPtr, nullPtr, nullPtr});
144}
145
146cir::CallOp CIRGenFunction::emitCoroAllocBuiltinCall(mlir::Location loc) {
147 cir::BoolType boolTy = builder.getBoolTy();
148
149 mlir::Operation *builtin = cgm.getGlobalValue(cgm.builtinCoroAlloc);
150
151 cir::FuncOp fnOp;
152 if (!builtin) {
153 fnOp = cgm.createCIRBuiltinFunction(loc, cgm.builtinCoroAlloc,
154 cir::FuncType::get({uInt32Ty}, boolTy),
155 /*fd=*/nullptr);
156 assert(fnOp && "should always succeed");
157 } else {
158 fnOp = cast<cir::FuncOp>(builtin);
159 }
160
161 return builder.createCallOp(
162 loc, fnOp, mlir::ValueRange{curCoro.data->coroId.getResult()});
163}
164
165cir::CallOp
167 mlir::Value coroframeAddr) {
168 mlir::Operation *builtin = cgm.getGlobalValue(cgm.builtinCoroBegin);
169
170 cir::FuncOp fnOp;
171 if (!builtin) {
172 fnOp = cgm.createCIRBuiltinFunction(
173 loc, cgm.builtinCoroBegin,
174 cir::FuncType::get({uInt32Ty, voidPtrTy}, voidPtrTy),
175 /*fd=*/nullptr);
176 assert(fnOp && "should always succeed");
177 } else {
178 fnOp = cast<cir::FuncOp>(builtin);
179 }
180
181 return builder.createCallOp(
182 loc, fnOp,
183 mlir::ValueRange{curCoro.data->coroId.getResult(), coroframeAddr});
184}
185
186mlir::LogicalResult
188 mlir::Location openCurlyLoc = getLoc(s.getBeginLoc());
189 cir::ConstantOp nullPtrCst = builder.getNullPtr(voidPtrTy, openCurlyLoc);
190
191 auto fn = mlir::cast<cir::FuncOp>(curFn);
192 fn.setCoroutine(true);
193 cir::CallOp coroId = emitCoroIDBuiltinCall(openCurlyLoc, nullPtrCst);
194 createCoroData(*this, curCoro, coroId);
195
196 // Backend is allowed to elide memory allocations, to help it, emit
197 // auto mem = coro.alloc() ? 0 : ... allocation code ...;
198 cir::CallOp coroAlloc = emitCoroAllocBuiltinCall(openCurlyLoc);
199
200 // Initialize address of coroutine frame to null
201 CanQualType astVoidPtrTy = cgm.getASTContext().VoidPtrTy;
202 mlir::Type allocaTy = convertTypeForMem(astVoidPtrTy);
203 Address coroFrame =
204 createTempAlloca(allocaTy, getContext().getTypeAlignInChars(astVoidPtrTy),
205 openCurlyLoc, "__coro_frame_addr",
206 /*ArraySize=*/nullptr);
207
208 mlir::Value storeAddr = coroFrame.getPointer();
209 builder.CIRBaseBuilderTy::createStore(openCurlyLoc, nullPtrCst, storeAddr);
210 cir::IfOp::create(
211 builder, openCurlyLoc, coroAlloc.getResult(),
212 /*withElseRegion=*/false,
213 /*thenBuilder=*/[&](mlir::OpBuilder &b, mlir::Location loc) {
214 builder.CIRBaseBuilderTy::createStore(
215 loc, emitScalarExpr(s.getAllocate()), storeAddr);
216 cir::YieldOp::create(builder, loc);
217 });
218 curCoro.data->coroBegin =
220 openCurlyLoc,
221 cir::LoadOp::create(builder, openCurlyLoc, allocaTy, storeAddr))
222 .getResult();
223
224 // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
225 if (s.getReturnStmtOnAllocFailure())
226 cgm.errorNYI("handle coroutine return alloc failure");
227
228 {
230 ParamReferenceReplacerRAII paramReplacer(localDeclMap);
231 // Create mapping between parameters and copy-params for coroutine
232 // function.
233 llvm::ArrayRef<const Stmt *> paramMoves = s.getParamMoves();
234 assert((paramMoves.size() == 0 || (paramMoves.size() == fnArgs.size())) &&
235 "ParamMoves and FnArgs should be the same size for coroutine "
236 "function");
237 // For zipping the arg map into debug info.
239
240 // Create parameter copies. We do it before creating a promise, since an
241 // evolution of coroutine TS may allow promise constructor to observe
242 // parameter copies.
244 for (auto *pm : paramMoves) {
245 if (emitStmt(pm, /*useCurrentScope=*/true).failed())
246 return mlir::failure();
247 paramReplacer.addCopy(cast<DeclStmt>(pm));
248 }
249
250 if (emitStmt(s.getPromiseDeclStmt(), /*useCurrentScope=*/true).failed())
251 return mlir::failure();
252 // returnValue should be valid as long as the coroutine's return type
253 // is not void. The assertion could help us to reduce the check later.
254 assert(returnValue.isValid() == (bool)s.getReturnStmt());
255 // Now we have the promise, initialize the GRO.
256 // We need to emit `get_return_object` first. According to:
257 // [dcl.fct.def.coroutine]p7
258 // The call to get_return_­object is sequenced before the call to
259 // initial_suspend and is invoked at most once.
260 //
261 // So we couldn't emit return value when we emit return statment,
262 // otherwise the call to get_return_object wouldn't be in front
263 // of initial_suspend.
264 if (returnValue.isValid())
265 emitAnyExprToMem(s.getReturnValue(), returnValue,
266 s.getReturnValue()->getType().getQualifiers(),
267 /*isInit*/ true);
268
270 // FIXME(cir): EHStack.pushCleanup<CallCoroEnd>(EHCleanup);
271 curCoro.data->currentAwaitKind = cir::AwaitKind::Init;
272 if (emitStmt(s.getInitSuspendStmt(), /*useCurrentScope=*/true).failed())
273 return mlir::failure();
275 }
276 return mlir::success();
277}
278
279static bool memberCallExpressionCanThrow(const Expr *e) {
280 if (const auto *ce = dyn_cast<CXXMemberCallExpr>(e))
281 if (const auto *proto =
282 ce->getMethodDecl()->getType()->getAs<FunctionProtoType>())
283 if (isNoexceptExceptionSpec(proto->getExceptionSpecType()) &&
284 proto->canThrow() == CT_Cannot)
285 return false;
286 return true;
287}
288
289// Given a suspend expression which roughly looks like:
290//
291// auto && x = CommonExpr();
292// if (!x.await_ready()) {
293// x.await_suspend(...); (*)
294// }
295// x.await_resume();
296//
297// where the result of the entire expression is the result of x.await_resume()
298//
299// (*) If x.await_suspend return type is bool, it allows to veto a suspend:
300// if (x.await_suspend(...))
301// llvm_coro_suspend();
302//
303// This is more higher level than LLVM codegen, for that one see llvm's
304// docs/Coroutines.rst for more details.
305namespace {
306struct LValueOrRValue {
307 LValue lv;
308 RValue rv;
309};
310} // namespace
311
312static LValueOrRValue
314 CoroutineSuspendExpr const &s, cir::AwaitKind kind,
315 AggValueSlot aggSlot, bool ignoreResult,
316 mlir::Block *scopeParentBlock,
317 mlir::Value &tmpResumeRValAddr, bool forLValue) {
318 [[maybe_unused]] mlir::LogicalResult awaitBuild = mlir::success();
319 LValueOrRValue awaitRes;
320
322 CIRGenFunction::OpaqueValueMapping(cgf, s.getOpaqueValue());
323 CIRGenBuilderTy &builder = cgf.getBuilder();
324 [[maybe_unused]] cir::AwaitOp awaitOp = cir::AwaitOp::create(
325 builder, cgf.getLoc(s.getSourceRange()), kind,
326 /*readyBuilder=*/
327 [&](mlir::OpBuilder &b, mlir::Location loc) {
328 Expr *condExpr = s.getReadyExpr()->IgnoreParens();
329 builder.createCondition(cgf.evaluateExprAsBool(condExpr));
330 },
331 /*suspendBuilder=*/
332 [&](mlir::OpBuilder &b, mlir::Location loc) {
333 // Note that differently from LLVM codegen we do not emit coro.save
334 // and coro.suspend here, that should be done as part of lowering this
335 // to LLVM dialect (or some other MLIR dialect)
336
337 // A invalid suspendRet indicates "void returning await_suspend"
338 mlir::Value suspendRet = cgf.emitScalarExpr(s.getSuspendExpr());
339
340 // Veto suspension if requested by bool returning await_suspend.
341 if (suspendRet) {
342 cgf.cgm.errorNYI("Veto await_suspend");
343 }
344
345 // Signals the parent that execution flows to next region.
346 cir::YieldOp::create(builder, loc);
347 },
348 /*resumeBuilder=*/
349 [&](mlir::OpBuilder &b, mlir::Location loc) {
350 // Exception handling requires additional IR. If the 'await_resume'
351 // function is marked as 'noexcept', we avoid generating this additional
352 // IR.
353 CXXTryStmt *tryStmt = nullptr;
354 if (coro.exceptionHandler && kind == cir::AwaitKind::Init &&
355 memberCallExpressionCanThrow(s.getResumeExpr()))
356 cgf.cgm.errorNYI("Coro resume Exception");
357
358 // FIXME(cir): the alloca for the resume expr should be placed in the
359 // enclosing cir.scope instead.
360 if (forLValue) {
362 } else {
363 awaitRes.rv =
364 cgf.emitAnyExpr(s.getResumeExpr(), aggSlot, ignoreResult);
365 if (!awaitRes.rv.isIgnored())
366 // Create the alloca in the block before the scope wrapping
367 // cir.await.
369 }
370
371 if (tryStmt)
372 cgf.cgm.errorNYI("Coro tryStmt");
373
374 // Returns control back to parent.
375 cir::YieldOp::create(builder, loc);
376 });
377
378 assert(awaitBuild.succeeded() && "Should know how to codegen");
379 return awaitRes;
380}
381
383 const CoroutineSuspendExpr &e,
384 cir::AwaitKind kind, AggValueSlot aggSlot,
385 bool ignoreResult) {
386 RValue rval;
387 mlir::Location scopeLoc = cgf.getLoc(e.getSourceRange());
388
389 // Since we model suspend / resume as an inner region, we must store
390 // resume scalar results in a tmp alloca, and load it after we build the
391 // suspend expression. An alternative way to do this would be to make
392 // every region return a value when promise.return_value() is used, but
393 // it's a bit awkward given that resume is the only region that actually
394 // returns a value.
395 mlir::Block *currEntryBlock = cgf.curLexScope->getEntryBlock();
396 [[maybe_unused]] mlir::Value tmpResumeRValAddr;
397
398 // No need to explicitly wrap this into a scope since the AST already uses a
399 // ExprWithCleanups, which will wrap this into a cir.scope anyways.
400 rval = emitSuspendExpression(cgf, *cgf.curCoro.data, e, kind, aggSlot,
401 ignoreResult, currEntryBlock, tmpResumeRValAddr,
402 /*forLValue*/ false)
403 .rv;
404
405 if (ignoreResult || rval.isIgnored())
406 return rval;
407
408 if (rval.isScalar()) {
409 rval = RValue::get(cir::LoadOp::create(cgf.getBuilder(), scopeLoc,
410 rval.getValue().getType(),
411 tmpResumeRValAddr));
412 } else if (rval.isAggregate()) {
413 // This is probably already handled via AggSlot, remove this assertion
414 // once we have a testcase and prove all pieces work.
415 cgf.cgm.errorNYI("emitSuspendExpr Aggregate");
416 } else { // complex
417 cgf.cgm.errorNYI("emitSuspendExpr Complex");
418 }
419 return rval;
420}
421
423 AggValueSlot aggSlot,
424 bool ignoreResult) {
425 return emitSuspendExpr(*this, e, curCoro.data->currentAwaitKind, aggSlot,
426 ignoreResult);
427}
static LValueOrRValue emitSuspendExpression(CIRGenFunction &cgf, CGCoroData &coro, CoroutineSuspendExpr const &s, cir::AwaitKind kind, AggValueSlot aggSlot, bool ignoreResult, mlir::Block *scopeParentBlock, mlir::Value &tmpResumeRValAddr, bool forLValue)
static RValue emitSuspendExpr(CIRGenFunction &cgf, const CoroutineSuspendExpr &e, cir::AwaitKind kind, AggValueSlot aggSlot, bool ignoreResult)
static bool memberCallExpressionCanThrow(const Expr *e)
static void createCoroData(CIRGenFunction &cgf, CIRGenFunction::CGCoroInfo &curCoro, cir::CallOp coroId)
__device__ __2f16 b
__device__ __2f16 float __ockl_bool s
__device__ __2f16 float c
mlir::Value getPointer() const
Definition Address.h:90
An aggregate value slot.
An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
cir::CallOp emitCoroIDBuiltinCall(mlir::Location loc, mlir::Value nullPtr)
cir::AllocaOp createTempAlloca(mlir::Type ty, mlir::Location loc, const Twine &name="tmp", mlir::Value arraySize=nullptr, bool insertIntoFnEntryBlock=false)
This creates an alloca and inserts it into the entry block if ArraySize is nullptr,...
llvm::DenseMap< const clang::Decl *, Address > DeclMapTy
mlir::Location getLoc(clang::SourceLocation srcLoc)
Helpers to convert Clang's SourceLocation to a MLIR Location.
void emitAnyExprToMem(const Expr *e, Address location, Qualifiers quals, bool isInitializer)
Emits the code necessary to evaluate an arbitrary expression into the given memory location.
mlir::Operation * curFn
The current function or global initializer that is generated code for.
llvm::SmallVector< const ParmVarDecl * > fnArgs
Save Parameter Decl for coroutine.
mlir::Type convertTypeForMem(QualType t)
cir::CallOp emitCoroAllocBuiltinCall(mlir::Location loc)
Address returnValue
The temporary alloca to hold the return value.
CIRGenBuilderTy & getBuilder()
DeclMapTy localDeclMap
This keeps track of the CIR allocas or globals for local C declarations.
RValue emitCoawaitExpr(const CoawaitExpr &e, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
clang::ASTContext & getContext() const
mlir::LogicalResult emitCoroutineBody(const CoroutineBodyStmt &s)
cir::CallOp emitCoroBeginBuiltinCall(mlir::Location loc, mlir::Value coroframeAddr)
mlir::LogicalResult emitStmt(const clang::Stmt *s, bool useCurrentScope, llvm::ArrayRef< const Attr * > attrs={})
DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef)
Helpers to emit "not yet implemented" error diagnostics.
This trivial value class is used to represent the result of an expression that is evaluated.
Definition CIRGenValue.h:33
bool isAggregate() const
Definition CIRGenValue.h:51
static RValue get(mlir::Value v)
Definition CIRGenValue.h:83
mlir::Value getValue() const
Return the value of this scalar value.
Definition CIRGenValue.h:57
bool isScalar() const
Definition CIRGenValue.h:49
bool isIgnored() const
Definition CIRGenValue.h:52
Represents a 'co_await' expression.
Definition ExprCXX.h:5369
Represents the body of a coroutine.
Definition StmtCXX.h:320
Represents an expression that might suspend coroutine execution; either a co_await or co_yield expres...
Definition ExprCXX.h:5255
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
ValueDecl * getDecl()
Definition Expr.h:1338
bool isSingleDecl() const
isSingleDecl - This method returns true if this DeclStmt refers to a single Decl.
Definition Stmt.h:1634
const Decl * getSingleDecl() const
Definition Stmt.h:1636
This represents one expression.
Definition Expr.h:112
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5254
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Stmt - This represents one statement.
Definition Stmt.h:85
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
Exposes information about the current target.
Definition TargetInfo.h:226
unsigned getNewAlign() const
Return the largest alignment for which a suitably-sized allocation with 'operator new(size_t)' is gua...
Definition TargetInfo.h:766
unsigned getCharWidth() const
Definition TargetInfo.h:520
const Expr * getInit() const
Definition Decl.h:1368
Defines the clang::TargetInfo interface.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isNoexceptExceptionSpec(ExceptionSpecificationType ESpecType)
U cast(CodeGen::Address addr)
Definition Address.h:327
static bool ehCleanupScope()
static bool coroCoReturn()
static bool emitBodyAndFallthrough()
static bool coroOutsideFrameMD()
static bool coroCoYield()
static bool generateDebugInfo()
std::unique_ptr< CGCoroData > data
cir::PointerType voidPtrTy
void* in address space 0