14#include "mlir/Support/LLVM.h"
68struct GetParamRef :
public StmtVisitor<GetParamRef> {
73 assert(
expr ==
nullptr &&
"multilple declref in param move");
76 void VisitStmt(
Stmt *s) {
87struct ParamReferenceReplacerRAII {
92 : localDeclMap(localDeclMap) {}
94 void addCopy(
const DeclStmt *pm) {
98 const VarDecl *vd =
static_cast<const VarDecl *
>(pm->
getSingleDecl());
99 const Expr *initExpr = vd->
getInit();
101 visitor.Visit(
const_cast<Expr *
>(initExpr));
102 assert(visitor.expr);
103 DeclRefExpr *dreOrig = visitor.expr;
106 auto it = localDeclMap.find(pd);
107 assert(it != localDeclMap.end() &&
"parameter is not found");
108 savedLocals.insert({pd, it->second});
110 auto copyIt = localDeclMap.find(vd);
111 assert(copyIt != localDeclMap.end() &&
"parameter copy is not found");
112 it->second = copyIt->getSecond();
115 ~ParamReferenceReplacerRAII() {
116 for (
auto &&savedLocal : savedLocals) {
117 localDeclMap.insert({savedLocal.first, savedLocal.second});
125struct CallCoroDelete final :
public EHScopeStack::Cleanup {
135 void emit(CIRGenFunction &cgf, Flags)
override {
140 if (cgf.
emitStmt(deallocate,
true).failed()) {
141 cgf.
cgm.
error(deallocate->getBeginLoc(),
142 "failed to emit coroutine deallocation expression");
147 cir::CoroFreeOp coroFree = cgf.
curCoro.
data->lastCoroFree;
150 cgf.
cgm.
error(deallocate->getBeginLoc(),
151 "Deallocation expression does not refer to coro.free");
155 builder.setInsertionPointAfter(coroFree);
158 llvm::SmallVector<mlir::Operation *> opsToMove;
159 mlir::Block *block = builder.getInsertionBlock();
160 mlir::Block::iterator it(isPtrNotNull.getDefiningOp());
162 for (++it; it != block->end(); ++it)
163 opsToMove.push_back(&*it);
166 cir::IfOp::create(builder, cgf.
getLoc(deallocate->getSourceRange()),
168 [&](mlir::OpBuilder &builder, mlir::Location loc) {
169 cir::YieldOp::create(builder, loc);
172 mlir::Operation *yieldOp = ifOp.getThenRegion().back().getTerminator();
173 for (
auto *op : opsToMove)
174 op->moveBefore(yieldOp);
176 explicit CallCoroDelete(Stmt *deallocStmt) : deallocate(deallocStmt) {}
190 cir::CoroIdOp coroId,
191 CallExpr const *coroIdExpr =
nullptr) {
195 cgf.
cgm.
error(coroIdExpr->getBeginLoc(),
196 "only one __builtin_coro_id can be used in a function");
198 cgf.
cgm.
error(coroIdExpr->getBeginLoc(),
199 "__builtin_coro_id shall not be used in a C++ coroutine");
201 llvm_unreachable(
"EmitCoroutineBodyStatement called twice?");
211static mlir::LogicalResult
215 if (cgf.
emitStmt(body,
true).failed())
216 return mlir::failure();
225 const bool canFallthrough = !currLexScope->
hasCoreturn();
228 if (cgf.
emitStmt(onFallthrough,
true).failed())
229 return mlir::failure();
231 return mlir::success();
241 auto coroId = cir::CoroIdOp::create(
cgm.getBuilder(), loc, args);
249 cgm.error(e->
getBeginLoc(),
"this builtin expect that __builtin_coro_id has"
250 " been used earlier in this function");
254 return cir::CoroAllocOp::create(
255 cgm.getBuilder(), loc,
256 mlir::ValueRange{curCoro.data->coroId.getResult()});
263 cgm.error(e->
getBeginLoc(),
"this builtin expect that __builtin_coro_id has"
264 " been used earlier in this function");
268 args.push_back(
curCoro.data->coroId.getResult());
272 auto coroBegin = cir::CoroBeginOp::create(
cgm.getBuilder(), loc, args);
273 curCoro.data->coroBegin = coroBegin;
284 args.push_back(cir::TokenNoneOp::create(builder, loc));
285 return cir::CoroEndOp::create(builder, loc, {
cgm.voidTy}, args);
292 cgm.error(e->
getBeginLoc(),
"this builtin expect that __builtin_coro_id has"
293 " been used earlier in this function");
298 cir::CoroFreeOp::create(
cgm.getBuilder(), loc,
299 mlir::ValueRange{curCoro.data->coroId.getResult(),
300 curCoro.data->coroBegin});
302 curCoro.data->lastCoroFree = coroFree;
308 return cir::CoroSizeOp::create(
cgm.getBuilder(), loc);
311static mlir::LogicalResult
325 ~handlerEmitter()
override =
default;
336 cir::ConstantOp nullPtrCst = builder.getNullPtr(
voidPtrTy, openCurlyLoc);
338 auto fn = mlir::cast<cir::FuncOp>(
curFn);
339 fn.setCoroutine(
true);
343 cir::CoroIdOp coroId = cir::CoroIdOp::create(
344 cgm.getBuilder(), openCurlyLoc,
345 mlir::ValueRange{builder.getUInt32(newAlign, openCurlyLoc), nullPtrCst,
346 nullPtrCst, nullPtrCst});
351 cir::CoroAllocOp coroAlloc = cir::CoroAllocOp::create(
352 cgm.getBuilder(), openCurlyLoc,
353 mlir::ValueRange{curCoro.data->coroId.getResult()});
360 openCurlyLoc,
"__coro_frame_addr",
363 mlir::Value storeAddr = coroFrame.
getPointer();
364 builder.CIRBaseBuilderTy::createStore(openCurlyLoc, nullPtrCst, storeAddr);
366 builder, openCurlyLoc, coroAlloc.getResult(),
368 [&](mlir::OpBuilder &b, mlir::Location loc) {
369 builder.CIRBaseBuilderTy::createStore(
370 loc, emitScalarExpr(s.getAllocate()), storeAddr);
371 cir::YieldOp::create(builder, loc);
373 curCoro.data->coroBegin = cir::CoroBeginOp::create(
374 cgm.getBuilder(), openCurlyLoc,
376 curCoro.data->coroId.getResult(),
377 cir::LoadOp::create(builder, openCurlyLoc, allocaTy, storeAddr)});
381 cgm.errorNYI(
"handle coroutine return alloc failure");
391 assert((paramMoves.size() == 0 || (paramMoves.size() ==
fnArgs.size())) &&
392 "ParamMoves and FnArgs should be the same size for coroutine "
401 for (
auto *pm : paramMoves) {
403 return mlir::failure();
408 return mlir::failure();
428 curCoro.data->currentAwaitKind = cir::AwaitKind::Init;
432 return mlir::failure();
434 curCoro.data->currentAwaitKind = cir::AwaitKind::User;
436 mlir::OpBuilder::InsertPoint userBody;
438 cir::CoroBodyOp::create(builder, openCurlyLoc,
439 [&](mlir::OpBuilder &b, mlir::Location loc) {
440 userBody = b.saveInsertionPoint();
443 mlir::OpBuilder::InsertionGuard guard(builder);
444 builder.restoreInsertionPoint(userBody);
445 if (
curCoro.data->exceptionHandler) {
461 if (
curCoro.data->resumeEHVar.isValid()) {
462 mlir::Value shouldSkip = builder.createFlagLoad(
463 openCurlyLoc,
curCoro.data->resumeEHVar.getPointer());
464 mlir::LogicalResult res = mlir::success();
465 cir::IfOp::create(builder, openCurlyLoc, shouldSkip,
467 [&](mlir::OpBuilder &b, mlir::Location loc) {
469 builder.createYield(openCurlyLoc);
473 return mlir::failure();
476 return mlir::failure();
480 return mlir::failure();
484 mlir::Block &coroBodyBlock = coroBodyOp.getBody().back();
485 if (!coroBodyBlock.mightHaveTerminator()) {
486 mlir::OpBuilder::InsertionGuard guard(builder);
487 builder.setInsertionPointToEnd(&coroBodyBlock);
488 cir::YieldOp::create(builder, openCurlyLoc);
499 const bool canFallthrough =
curLexScope->hasCoreturn();
500 const bool hasCoreturns =
curCoro.data->coreturnCount > 0;
501 if (canFallthrough || hasCoreturns) {
502 curCoro.data->currentAwaitKind = cir::AwaitKind::Final;
504 mlir::OpBuilder::InsertionGuard guard(builder);
507 return mlir::failure();
512 cir::ConstantOp nullHandler =
513 builder.getNullPtr(builder.getVoidPtrTy(), openCurlyLoc);
514 cir::ConstantOp noUnwind = builder.getBool(
false, openCurlyLoc);
515 auto tkNone = cir::TokenNoneOp::create(builder, openCurlyLoc);
516 cir::CoroEndOp::create(builder, openCurlyLoc, nullHandler, noUnwind, tkNone);
518 if (
auto *ret = cast_or_null<ReturnStmt>(s.
getReturnStmt())) {
521 Expr *previousRetValue = ret->getRetValue();
522 ret->setRetValue(
nullptr);
524 return mlir::failure();
527 ret->setRetValue(previousRetValue);
529 return mlir::success();
533 if (
const auto *ce = dyn_cast<CXXMemberCallExpr>(e))
534 if (
const auto *proto =
559struct LValueOrRValue {
569 mlir::Block *scopeParentBlock,
570 mlir::Value &tmpResumeRValAddr,
bool forLValue) {
571 [[maybe_unused]] mlir::LogicalResult awaitBuild = mlir::success();
572 LValueOrRValue awaitRes;
577 [[maybe_unused]] cir::AwaitOp awaitOp = cir::AwaitOp::create(
580 [&](mlir::OpBuilder &b, mlir::Location loc) {
581 Expr *condExpr = s.getReadyExpr()->IgnoreParens();
582 builder.createCondition(cgf.evaluateExprAsBool(condExpr));
585 [&](mlir::OpBuilder &b, mlir::Location loc) {
591 mlir::Value suspendRet = cgf.emitScalarExpr(s.getSuspendExpr());
595 cgf.cgm.errorNYI(
"Veto await_suspend");
599 cir::YieldOp::create(builder, loc);
602 [&](mlir::OpBuilder &b, mlir::Location loc) {
606 if (coro.exceptionHandler &&
kind == cir::AwaitKind::Init &&
619 SourceLocation resumeLoc = s.getResumeExpr()->getExprLoc();
620 mlir::Location mlirLoc = cgf.
getLoc(resumeLoc);
624 builder.createFlagStore(mlirLoc,
false,
625 coro.resumeEHVar.getPointer());
627 CXXCatchStmt catchStmt(resumeLoc,
628 nullptr, coro.exceptionHandler);
631 resumeLoc, resumeLoc);
632 CXXTryStmt *tryStmt =
635 struct resumeEmitter final : CIRGenFunction::cxxTryBodyEmitter {
636 const CXXTryStmt &tryStmt;
638 mlir::Value resumeEHVar;
639 resumeEmitter(
const CXXTryStmt &tryStmt, mlir::Location loc,
641 : tryStmt(tryStmt), loc(loc),
642 resumeEHVar(resumeEHVar.getPointer()) {}
644 mlir::LogicalResult operator()(CIRGenFunction &cgf)
override {
645 mlir::LogicalResult res =
646 cgf.
emitStmt(tryStmt.getTryBlock(),
true);
651 ~resumeEmitter()
override =
default;
652 } emitter{*tryStmt, mlirLoc, coro.resumeEHVar};
658 }
else if (forLValue) {
661 awaitRes.lv = cgf.
emitLValue(s.getResumeExpr());
664 cgf.
emitAnyExpr(s.getResumeExpr(), aggSlot, ignoreResult);
665 if (!awaitRes.rv.isIgnored()) {
669 RValue rv = awaitRes.rv;
675 cgf.
cgm.
errorNYI(
"emitSuspendExpression: Aggregate value");
681 builder.getBestAllocaInsertPoint(scopeParentBlock));
683 builder.CIRBaseBuilderTy::createStore(loc, value,
689 cir::YieldOp::create(builder, loc);
692 assert(awaitBuild.succeeded() &&
"Should know how to codegen");
710 [[maybe_unused]] mlir::Value tmpResumeRValAddr;
715 ignoreResult, currEntryBlock, tmpResumeRValAddr,
765 return mlir::failure();
770 cir::CoReturnOp::create(builder, loc);
772 return mlir::success();
static void emit(Program &P, llvm::SmallVectorImpl< std::byte > &Code, const T &Val, bool &Success)
Helper to write bytecode and bail out if 32-bit offsets become invalid.
static void createCoroData(CIRGenFunction &cgf, CIRGenFunction::CGCoroInfo &curCoro, cir::CoroIdOp coroId, CallExpr const *coroIdExpr=nullptr)
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 mlir::LogicalResult coroutineBodyExceptionHelper(CIRGenFunction &cgf, const CoroutineBodyStmt &s)
static mlir::LogicalResult emitBodyAndFallthrough(CIRGenFunction &cgf, const CoroutineBodyStmt &s, Stmt *body, const CIRGenFunction::LexicalScope *currLexScope)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
cir::StoreOp createFlagStore(mlir::Location loc, bool val, mlir::Value dst)
mlir::Value createPtrIsNotNull(mlir::Value ptr)
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
mlir::Value getPointer() const
An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited.
mlir::LogicalResult emitCoreturnStmt(const CoreturnStmt &s)
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,...
cir::CoroAllocOp emitCoroAllocBuiltinCall(const CallExpr *e)
llvm::DenseMap< const clang::Decl *, Address > DeclMapTy
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.
cir::CoroBeginOp emitCoroBeginBuiltinCall(const CallExpr *e)
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.
RValue emitCoyieldExpr(const CoyieldExpr &e, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
cir::CoroFreeOp emitCoroFreeBuiltin(const CallExpr *e)
mlir::Operation * curFn
The current function or global initializer that is generated code for.
EHScopeStack ehStack
Tracks function scope overall cleanup handling.
llvm::SmallVector< const ParmVarDecl * > fnArgs
Save Parameter Decl for coroutine.
mlir::Type convertTypeForMem(QualType t)
mlir::LogicalResult emitCXXTryStmt(const clang::CXXTryStmt &s, cxxTryBodyEmitter &bodyCallback)
RValue emitCoroutineFrame()
mlir::Value emitAlloca(llvm::StringRef name, mlir::Type ty, mlir::Location loc, clang::CharUnits alignment, bool insertIntoFnEntryBlock, mlir::Value arraySize=nullptr)
Address returnValue
The temporary alloca to hold the return value.
cir::CoroEndOp emitCoroEndBuiltinCall(const CallExpr *e)
mlir::Value emitScalarExpr(const clang::Expr *e, bool ignoreResultAssign=false)
Emit the computation of the specified expression of scalar type.
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)
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.
cir::CoroSizeOp emitCoroSizeBuiltinCall(const CallExpr *e)
LexicalScope * curLexScope
cir::CoroIdOp emitCoroIDBuiltinCall(const CallExpr *e)
clang::ASTContext & getContext() const
mlir::LogicalResult emitCoroutineBody(const CoroutineBodyStmt &s)
mlir::LogicalResult emitStmt(const clang::Stmt *s, bool useCurrentScope, llvm::ArrayRef< const Attr * > attrs={})
void emitIgnoredExpr(const clang::Expr *e)
Emit code to compute the specified expression, ignoring the result.
DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef)
Helpers to emit "not yet implemented" error diagnostics.
void error(SourceLocation loc, llvm::StringRef error)
Emit a general error that something can't be done.
This trivial value class is used to represent the result of an expression that is evaluated.
static RValue get(mlir::Value v)
static RValue getComplex(mlir::Value v)
mlir::Value getValue() const
Return the value of this scalar value.
mlir::Value getComplexValue() const
Return the value of this complex value.
static RValue getIgnored()
CXXCatchStmt - This represents a C++ catch block.
static CXXTryStmt * Create(const ASTContext &C, SourceLocation tryLoc, CompoundStmt *tryBlock, ArrayRef< Stmt * > handlers)
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
SourceLocation getBeginLoc() const
static CharUnits One()
One - Construct a CharUnits quantity of one.
Represents a 'co_await' expression.
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
Represents a 'co_return' statement in the C++ Coroutines TS.
Expr * getOperand() const
Retrieve the operand of the 'co_return' statement.
Expr * getPromiseCall() const
Retrieve the promise call that results from this 'co_return' statement.
Represents the body of a coroutine.
CompoundStmt * getBody() const
Retrieve the body of the coroutine as written.
Stmt * getReturnStmtOnAllocFailure() const
Stmt * getReturnStmt() const
Stmt * getInitSuspendStmt() const
Stmt * getPromiseDeclStmt() const
Expr * getDeallocate() const
Stmt * getFallthroughHandler() const
Stmt * getExceptionHandler() const
SourceLocation getBeginLoc() const LLVM_READONLY
Expr * getReturnValue() const
Stmt * getFinalSuspendStmt() const
ArrayRef< Stmt const * > getParamMoves() const
Represents an expression that might suspend coroutine execution; either a co_await or co_yield expres...
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Represents a 'co_yield' expression.
A reference to a declared variable, function, enum, etc.
bool isSingleDecl() const
isSingleDecl - This method returns true if this DeclStmt refers to a single Decl.
const Decl * getSingleDecl() const
This represents one expression.
Represents a prototype with parameter type info, e.g.
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Stmt - This represents one statement.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Exposes information about the current target.
unsigned getNewAlign() const
Return the largest alignment for which a suitably-sized allocation with 'operator new(size_t)' is gua...
unsigned getCharWidth() const
const Expr * getInit() const
Defines the clang::TargetInfo interface.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
bool isNoexceptExceptionSpec(ExceptionSpecificationType ESpecType)
U cast(CodeGen::Address addr)
static bool ehCleanupScope()
static bool coroOutsideFrameMD()
static bool generateDebugInfo()
cir::AwaitKind currentAwaitKind
CallExpr const * coroIdExpr
cir::CoroFreeOp lastCoroFree
std::unique_ptr< CGCoroData > data
Represents a scope, including function bodies, compound statements, and the substatements of if/while...
mlir::Block * getEntryBlock()
cir::PointerType voidPtrTy
void* in address space 0