#include "CGCleanup.h"
#include "CodeGenFunction.h"
#include "llvm/ADT/ScopeExit.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/StmtVisitor.h"
using namespace clang;
using namespace CodeGen;
using llvm::Value;
using llvm::BasicBlock;
namespace {
enum class AwaitKind { Init, Normal, Yield, Final };
static constexpr llvm::StringLiteral AwaitKindStr[] = {"init", "await", "yield",
"final"};
}
struct clang::CodeGen::CGCoroData {
AwaitKind CurrentAwaitKind = AwaitKind::Init;
unsigned AwaitNum = 0;
unsigned YieldNum = 0;
unsigned CoreturnCount = 0;
llvm::BasicBlock *SuspendBB = nullptr;
Stmt *ExceptionHandler = nullptr;
llvm::Value *ResumeEHVar = nullptr;
CodeGenFunction::JumpDest CleanupJD;
CodeGenFunction::JumpDest FinalJD;
llvm::CallInst *CoroId = nullptr;
llvm::CallInst *CoroBegin = nullptr;
llvm::CallInst *LastCoroFree = nullptr;
CallExpr const *CoroIdExpr = nullptr;
};
clang::CodeGen::CodeGenFunction::CGCoroInfo::CGCoroInfo() {}
CodeGenFunction::CGCoroInfo::~CGCoroInfo() {}
static void createCoroData(CodeGenFunction &CGF,
CodeGenFunction::CGCoroInfo &CurCoro,
llvm::CallInst *CoroId,
CallExpr const *CoroIdExpr = nullptr) {
if (CurCoro.Data) {
if (CurCoro.Data->CoroIdExpr)
CGF.CGM.Error(CoroIdExpr->getBeginLoc(),
"only one __builtin_coro_id can be used in a function");
else if (CoroIdExpr)
CGF.CGM.Error(CoroIdExpr->getBeginLoc(),
"__builtin_coro_id shall not be used in a C++ coroutine");
else
llvm_unreachable("EmitCoroutineBodyStatement called twice?");
return;
}
CurCoro.Data = std::unique_ptr<CGCoroData>(new CGCoroData);
CurCoro.Data->CoroId = CoroId;
CurCoro.Data->CoroIdExpr = CoroIdExpr;
}
static SmallString<32> buildSuspendPrefixStr(CGCoroData &Coro, AwaitKind Kind) {
unsigned No = 0;
switch (Kind) {
case AwaitKind::Init:
case AwaitKind::Final:
break;
case AwaitKind::Normal:
No = ++Coro.AwaitNum;
break;
case AwaitKind::Yield:
No = ++Coro.YieldNum;
break;
}
SmallString<32> Prefix(AwaitKindStr[static_cast<unsigned>(Kind)]);
if (No > 1) {
Twine(No).toVector(Prefix);
}
return Prefix;
}
static bool memberCallExpressionCanThrow(const Expr *E) {
if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
if (const auto *Proto =
CE->getMethodDecl()->getType()->getAs<FunctionProtoType>())
if (isNoexceptExceptionSpec(Proto->getExceptionSpecType()) &&
Proto->canThrow() == CT_Cannot)
return false;
return true;
}
namespace {
struct LValueOrRValue {
LValue LV;
RValue RV;
};
}
static LValueOrRValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro,
CoroutineSuspendExpr const &S,
AwaitKind Kind, AggValueSlot aggSlot,
bool ignoreResult, bool forLValue) {
auto *E = S.getCommonExpr();
auto Binder =
CodeGenFunction::OpaqueValueMappingData::bind(CGF, S.getOpaqueValue(), E);
auto UnbindOnExit = llvm::make_scope_exit([&] { Binder.unbind(CGF); });
auto Prefix = buildSuspendPrefixStr(Coro, Kind);
BasicBlock *ReadyBlock = CGF.createBasicBlock(Prefix + Twine(".ready"));
BasicBlock *SuspendBlock = CGF.createBasicBlock(Prefix + Twine(".suspend"));
BasicBlock *CleanupBlock = CGF.createBasicBlock(Prefix + Twine(".cleanup"));
CGF.EmitBranchOnBoolExpr(S.getReadyExpr(), ReadyBlock, SuspendBlock, 0);
CGF.EmitBlock(SuspendBlock);
auto &Builder = CGF.Builder;
llvm::Function *CoroSave = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_save);
auto *NullPtr = llvm::ConstantPointerNull::get(CGF.CGM.Int8PtrTy);
auto *SaveCall = Builder.CreateCall(CoroSave, {NullPtr});
auto *SuspendRet = CGF.EmitScalarExpr(S.getSuspendExpr());
if (SuspendRet != nullptr && SuspendRet->getType()->isIntegerTy(1)) {
BasicBlock *RealSuspendBlock =
CGF.createBasicBlock(Prefix + Twine(".suspend.bool"));
CGF.Builder.CreateCondBr(SuspendRet, RealSuspendBlock, ReadyBlock);
CGF.EmitBlock(RealSuspendBlock);
}
const bool IsFinalSuspend = (Kind == AwaitKind::Final);
llvm::Function *CoroSuspend =
CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_suspend);
auto *SuspendResult = Builder.CreateCall(
CoroSuspend, {SaveCall, Builder.getInt1(IsFinalSuspend)});
auto *Switch = Builder.CreateSwitch(SuspendResult, Coro.SuspendBB, 2);
Switch->addCase(Builder.getInt8(0), ReadyBlock);
Switch->addCase(Builder.getInt8(1), CleanupBlock);
CGF.EmitBlock(CleanupBlock);
CGF.EmitBranchThroughCleanup(Coro.CleanupJD);
CGF.EmitBlock(ReadyBlock);
CXXTryStmt *TryStmt = nullptr;
if (Coro.ExceptionHandler && Kind == AwaitKind::Init &&
memberCallExpressionCanThrow(S.getResumeExpr())) {
Coro.ResumeEHVar =
CGF.CreateTempAlloca(Builder.getInt1Ty(), Prefix + Twine("resume.eh"));
Builder.CreateFlagStore(true, Coro.ResumeEHVar);
auto Loc = S.getResumeExpr()->getExprLoc();
auto *Catch = new (CGF.getContext())
CXXCatchStmt(Loc, nullptr, Coro.ExceptionHandler);
auto *TryBody = CompoundStmt::Create(CGF.getContext(), S.getResumeExpr(),
FPOptionsOverride(), Loc, Loc);
TryStmt = CXXTryStmt::Create(CGF.getContext(), Loc, TryBody, Catch);
CGF.EnterCXXTryStmt(*TryStmt);
}
LValueOrRValue Res;
if (forLValue)
Res.LV = CGF.EmitLValue(S.getResumeExpr());
else
Res.RV = CGF.EmitAnyExpr(S.getResumeExpr(), aggSlot, ignoreResult);
if (TryStmt) {
Builder.CreateFlagStore(false, Coro.ResumeEHVar);
CGF.ExitCXXTryStmt(*TryStmt);
}
return Res;
}
RValue CodeGenFunction::EmitCoawaitExpr(const CoawaitExpr &E,
AggValueSlot aggSlot,
bool ignoreResult) {
return emitSuspendExpression(*this, *CurCoro.Data, E,
CurCoro.Data->CurrentAwaitKind, aggSlot,
ignoreResult, false).RV;
}
RValue CodeGenFunction::EmitCoyieldExpr(const CoyieldExpr &E,
AggValueSlot aggSlot,
bool ignoreResult) {
return emitSuspendExpression(*this, *CurCoro.Data, E, AwaitKind::Yield,
aggSlot, ignoreResult, false).RV;
}
void CodeGenFunction::EmitCoreturnStmt(CoreturnStmt const &S) {
++CurCoro.Data->CoreturnCount;
const Expr *RV = S.getOperand();
if (RV && RV->getType()->isVoidType() && !isa<InitListExpr>(RV)) {
RunCleanupsScope cleanupScope(*this);
EmitIgnoredExpr(RV);
}
EmitStmt(S.getPromiseCall());
EmitBranchThroughCleanup(CurCoro.Data->FinalJD);
}
#ifndef NDEBUG
static QualType getCoroutineSuspendExprReturnType(const ASTContext &Ctx,
const CoroutineSuspendExpr *E) {
const auto *RE = E->getResumeExpr();
assert(isa<CallExpr>(RE) && "unexpected suspend expression type");
return cast<CallExpr>(RE)->getCallReturnType(Ctx);
}
#endif
LValue
CodeGenFunction::EmitCoawaitLValue(const CoawaitExpr *E) {
assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
"Can't have a scalar return unless the return type is a "
"reference type!");
return emitSuspendExpression(*this, *CurCoro.Data, *E,
CurCoro.Data->CurrentAwaitKind, AggValueSlot::ignored(),
false, true).LV;
}
LValue
CodeGenFunction::EmitCoyieldLValue(const CoyieldExpr *E) {
assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
"Can't have a scalar return unless the return type is a "
"reference type!");
return emitSuspendExpression(*this, *CurCoro.Data, *E,
AwaitKind::Yield, AggValueSlot::ignored(),
false, true).LV;
}
namespace {
struct GetParamRef : public StmtVisitor<GetParamRef> {
public:
DeclRefExpr *Expr = nullptr;
GetParamRef() {}
void VisitDeclRefExpr(DeclRefExpr *E) {
assert(Expr == nullptr && "multilple declref in param move");
Expr = E;
}
void VisitStmt(Stmt *S) {
for (auto *C : S->children()) {
if (C)
Visit(C);
}
}
};
}
namespace {
struct ParamReferenceReplacerRAII {
CodeGenFunction::DeclMapTy SavedLocals;
CodeGenFunction::DeclMapTy& LocalDeclMap;
ParamReferenceReplacerRAII(CodeGenFunction::DeclMapTy &LocalDeclMap)
: LocalDeclMap(LocalDeclMap) {}
void addCopy(DeclStmt const *PM) {
assert(PM->isSingleDecl());
VarDecl const*VD = static_cast<VarDecl const*>(PM->getSingleDecl());
Expr const *InitExpr = VD->getInit();
GetParamRef Visitor;
Visitor.Visit(const_cast<Expr*>(InitExpr));
assert(Visitor.Expr);
DeclRefExpr *DREOrig = Visitor.Expr;
auto *PD = DREOrig->getDecl();
auto it = LocalDeclMap.find(PD);
assert(it != LocalDeclMap.end() && "parameter is not found");
SavedLocals.insert({ PD, it->second });
auto copyIt = LocalDeclMap.find(VD);
assert(copyIt != LocalDeclMap.end() && "parameter copy is not found");
it->second = copyIt->getSecond();
}
~ParamReferenceReplacerRAII() {
for (auto&& SavedLocal : SavedLocals) {
LocalDeclMap.insert({SavedLocal.first, SavedLocal.second});
}
}
};
}
static SmallVector<llvm::OperandBundleDef, 1>
getBundlesForCoroEnd(CodeGenFunction &CGF) {
SmallVector<llvm::OperandBundleDef, 1> BundleList;
if (llvm::Instruction *EHPad = CGF.CurrentFuncletPad)
BundleList.emplace_back("funclet", EHPad);
return BundleList;
}
namespace {
struct CallCoroEnd final : public EHScopeStack::Cleanup {
void Emit(CodeGenFunction &CGF, Flags flags) override {
auto &CGM = CGF.CGM;
auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
llvm::Function *CoroEndFn = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
auto Bundles = getBundlesForCoroEnd(CGF);
auto *CoroEnd = CGF.Builder.CreateCall(
CoroEndFn, {NullPtr, CGF.Builder.getTrue()}, Bundles);
if (Bundles.empty()) {
auto *ResumeBB = CGF.getEHResumeBlock(true);
auto *CleanupContBB = CGF.createBasicBlock("cleanup.cont");
CGF.Builder.CreateCondBr(CoroEnd, ResumeBB, CleanupContBB);
CGF.EmitBlock(CleanupContBB);
}
}
};
}
namespace {
struct CallCoroDelete final : public EHScopeStack::Cleanup {
Stmt *Deallocate;
void Emit(CodeGenFunction &CGF, Flags) override {
BasicBlock *SaveInsertBlock = CGF.Builder.GetInsertBlock();
auto *FreeBB = CGF.createBasicBlock("coro.free");
CGF.EmitBlock(FreeBB);
CGF.EmitStmt(Deallocate);
auto *AfterFreeBB = CGF.createBasicBlock("after.coro.free");
CGF.EmitBlock(AfterFreeBB);
auto *CoroFree = CGF.CurCoro.Data->LastCoroFree;
if (!CoroFree) {
CGF.CGM.Error(Deallocate->getBeginLoc(),
"Deallocation expressoin does not refer to coro.free");
return;
}
auto *InsertPt = SaveInsertBlock->getTerminator();
CoroFree->moveBefore(InsertPt);
CGF.Builder.SetInsertPoint(InsertPt);
auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
auto *Cond = CGF.Builder.CreateICmpNE(CoroFree, NullPtr);
CGF.Builder.CreateCondBr(Cond, FreeBB, AfterFreeBB);
InsertPt->eraseFromParent();
CGF.Builder.SetInsertPoint(AfterFreeBB);
}
explicit CallCoroDelete(Stmt *DeallocStmt) : Deallocate(DeallocStmt) {}
};
}
static void emitBodyAndFallthrough(CodeGenFunction &CGF,
const CoroutineBodyStmt &S, Stmt *Body) {
CGF.EmitStmt(Body);
const bool CanFallthrough = CGF.Builder.GetInsertBlock();
if (CanFallthrough)
if (Stmt *OnFallthrough = S.getFallthroughHandler())
CGF.EmitStmt(OnFallthrough);
}
void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt &S) {
auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
auto &TI = CGM.getContext().getTargetInfo();
unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();
auto *EntryBB = Builder.GetInsertBlock();
auto *AllocBB = createBasicBlock("coro.alloc");
auto *InitBB = createBasicBlock("coro.init");
auto *FinalBB = createBasicBlock("coro.final");
auto *RetBB = createBasicBlock("coro.ret");
auto *CoroId = Builder.CreateCall(
CGM.getIntrinsic(llvm::Intrinsic::coro_id),
{Builder.getInt32(NewAlign), NullPtr, NullPtr, NullPtr});
createCoroData(*this, CurCoro, CoroId);
CurCoro.Data->SuspendBB = RetBB;
assert(ShouldEmitLifetimeMarkers &&
"Must emit lifetime intrinsics for coroutines");
auto *CoroAlloc = Builder.CreateCall(
CGM.getIntrinsic(llvm::Intrinsic::coro_alloc), {CoroId});
Builder.CreateCondBr(CoroAlloc, AllocBB, InitBB);
EmitBlock(AllocBB);
auto *AllocateCall = EmitScalarExpr(S.getAllocate());
auto *AllocOrInvokeContBB = Builder.GetInsertBlock();
if (auto *RetOnAllocFailure = S.getReturnStmtOnAllocFailure()) {
auto *RetOnFailureBB = createBasicBlock("coro.ret.on.failure");
auto *NullPtr = llvm::ConstantPointerNull::get(Int8PtrTy);
auto *Cond = Builder.CreateICmpNE(AllocateCall, NullPtr);
Builder.CreateCondBr(Cond, InitBB, RetOnFailureBB);
EmitBlock(RetOnFailureBB);
EmitStmt(RetOnAllocFailure);
}
else {
Builder.CreateBr(InitBB);
}
EmitBlock(InitBB);
auto *Phi = Builder.CreatePHI(VoidPtrTy, 2);
Phi->addIncoming(NullPtr, EntryBB);
Phi->addIncoming(AllocateCall, AllocOrInvokeContBB);
auto *CoroBegin = Builder.CreateCall(
CGM.getIntrinsic(llvm::Intrinsic::coro_begin), {CoroId, Phi});
CurCoro.Data->CoroBegin = CoroBegin;
CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(RetBB);
{
CGDebugInfo *DI = getDebugInfo();
ParamReferenceReplacerRAII ParamReplacer(LocalDeclMap);
CodeGenFunction::RunCleanupsScope ResumeScope(*this);
EHStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, S.getDeallocate());
auto ParamMoves = S.getParamMoves();
assert(
(ParamMoves.size() == 0 || (ParamMoves.size() == FnArgs.size())) &&
"ParamMoves and FnArgs should be the same size for coroutine function");
if (ParamMoves.size() == FnArgs.size() && DI)
for (const auto Pair : llvm::zip(FnArgs, ParamMoves))
DI->getCoroutineParameterMappings().insert(
{std::get<0>(Pair), std::get<1>(Pair)});
for (auto *PM : S.getParamMoves()) {
EmitStmt(PM);
ParamReplacer.addCopy(cast<DeclStmt>(PM));
}
EmitStmt(S.getPromiseDeclStmt());
Address PromiseAddr = GetAddrOfLocalVar(S.getPromiseDecl());
auto *PromiseAddrVoidPtr =
new llvm::BitCastInst(PromiseAddr.getPointer(), VoidPtrTy, "", CoroId);
CoroId->setArgOperand(1, PromiseAddrVoidPtr);
assert(ReturnValue.isValid() == (bool)S.getReturnStmt());
if (ReturnValue.isValid()) {
EmitAnyExprToMem(S.getReturnValue(), ReturnValue,
S.getReturnValue()->getType().getQualifiers(),
true);
}
EHStack.pushCleanup<CallCoroEnd>(EHCleanup);
CurCoro.Data->CurrentAwaitKind = AwaitKind::Init;
CurCoro.Data->ExceptionHandler = S.getExceptionHandler();
EmitStmt(S.getInitSuspendStmt());
CurCoro.Data->FinalJD = getJumpDestInCurrentScope(FinalBB);
CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal;
if (CurCoro.Data->ExceptionHandler) {
BasicBlock *ContBB = nullptr;
if (CurCoro.Data->ResumeEHVar) {
BasicBlock *BodyBB = createBasicBlock("coro.resumed.body");
ContBB = createBasicBlock("coro.resumed.cont");
Value *SkipBody = Builder.CreateFlagLoad(CurCoro.Data->ResumeEHVar,
"coro.resumed.eh");
Builder.CreateCondBr(SkipBody, ContBB, BodyBB);
EmitBlock(BodyBB);
}
auto Loc = S.getBeginLoc();
CXXCatchStmt Catch(Loc, nullptr,
CurCoro.Data->ExceptionHandler);
auto *TryStmt =
CXXTryStmt::Create(getContext(), Loc, S.getBody(), &Catch);
EnterCXXTryStmt(*TryStmt);
emitBodyAndFallthrough(*this, S, TryStmt->getTryBlock());
ExitCXXTryStmt(*TryStmt);
if (ContBB)
EmitBlock(ContBB);
}
else {
emitBodyAndFallthrough(*this, S, S.getBody());
}
const bool CanFallthrough = Builder.GetInsertBlock();
const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0;
if (CanFallthrough || HasCoreturns) {
EmitBlock(FinalBB);
CurCoro.Data->CurrentAwaitKind = AwaitKind::Final;
EmitStmt(S.getFinalSuspendStmt());
} else {
EmitBlock(FinalBB, true);
}
}
EmitBlock(RetBB);
llvm::Function *CoroEnd = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
Builder.CreateCall(CoroEnd, {NullPtr, Builder.getFalse()});
if (Stmt *Ret = S.getReturnStmt()) {
cast<ReturnStmt>(Ret)->setRetValue(nullptr);
EmitStmt(Ret);
}
CurFn->setPresplitCoroutine();
}
RValue CodeGenFunction::EmitCoroutineIntrinsic(const CallExpr *E,
unsigned int IID) {
SmallVector<llvm::Value *, 8> Args;
switch (IID) {
default:
break;
case llvm::Intrinsic::coro_frame: {
if (CurCoro.Data && CurCoro.Data->CoroBegin) {
return RValue::get(CurCoro.Data->CoroBegin);
}
CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_begin "
"has been used earlier in this function");
auto NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
return RValue::get(NullPtr);
}
case llvm::Intrinsic::coro_alloc:
case llvm::Intrinsic::coro_begin:
case llvm::Intrinsic::coro_free: {
if (CurCoro.Data && CurCoro.Data->CoroId) {
Args.push_back(CurCoro.Data->CoroId);
break;
}
CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_id has"
" been used earlier in this function");
LLVM_FALLTHROUGH;
}
case llvm::Intrinsic::coro_suspend:
Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
break;
}
for (const Expr *Arg : E->arguments())
Args.push_back(EmitScalarExpr(Arg));
llvm::Function *F = CGM.getIntrinsic(IID);
llvm::CallInst *Call = Builder.CreateCall(F, Args);
if (IID == llvm::Intrinsic::coro_id) {
createCoroData(*this, CurCoro, Call, E);
}
else if (IID == llvm::Intrinsic::coro_begin) {
if (CurCoro.Data)
CurCoro.Data->CoroBegin = Call;
}
else if (IID == llvm::Intrinsic::coro_free) {
if (CurCoro.Data)
CurCoro.Data->LastCoroFree = Call;
}
return RValue::get(Call);
}