#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::make_unique<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 FunctionCanThrow(const FunctionDecl *D) {
const auto *Proto = D->getType()->getAs<FunctionProtoType>();
if (!Proto) {
return true;
}
return !isNoexceptExceptionSpec(Proto->getExceptionSpecType()) ||
Proto->canThrow() != CT_Cannot;
}
static bool StmtCanThrow(const Stmt *S) {
if (const auto *CE = dyn_cast<CallExpr>(S)) {
const auto *Callee = CE->getDirectCallee();
if (!Callee)
return true;
if (FunctionCanThrow(Callee))
return true;
}
if (const auto *TE = dyn_cast<CXXBindTemporaryExpr>(S)) {
const auto *Dtor = TE->getTemporary()->getDestructor();
if (FunctionCanThrow(Dtor))
return true;
}
for (const auto *child : S->children())
if (StmtCanThrow(child))
return true;
return false;
}
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 CommonBinder =
CodeGenFunction::OpaqueValueMappingData::bind(CGF, S.getOpaqueValue(), E);
auto UnbindCommonOnExit =
llvm::make_scope_exit([&] { CommonBinder.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 SuspendWrapper = CodeGenFunction(CGF.CGM).generateAwaitSuspendWrapper(
CGF.CurFn->getName(), Prefix, S);
CGF.CurCoro.InSuspendBlock = true;
assert(CGF.CurCoro.Data && CGF.CurCoro.Data->CoroBegin &&
"expected to be called in coroutine context");
SmallVector<llvm::Value *, 3> SuspendIntrinsicCallArgs;
SuspendIntrinsicCallArgs.push_back(
CGF.getOrCreateOpaqueLValueMapping(S.getOpaqueValue()).getPointer(CGF));
SuspendIntrinsicCallArgs.push_back(CGF.CurCoro.Data->CoroBegin);
SuspendIntrinsicCallArgs.push_back(SuspendWrapper);
const auto SuspendReturnType = S.getSuspendReturnType();
llvm::Intrinsic::ID AwaitSuspendIID;
switch (SuspendReturnType) {
case CoroutineSuspendExpr::SuspendReturnType::SuspendVoid:
AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_void;
break;
case CoroutineSuspendExpr::SuspendReturnType::SuspendBool:
AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_bool;
break;
case CoroutineSuspendExpr::SuspendReturnType::SuspendHandle:
AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_handle;
break;
}
llvm::Function *AwaitSuspendIntrinsic = CGF.CGM.getIntrinsic(AwaitSuspendIID);
const bool AwaitSuspendCanThrow =
SuspendReturnType ==
CoroutineSuspendExpr::SuspendReturnType::SuspendHandle ||
StmtCanThrow(S.getSuspendExpr());
llvm::CallBase *SuspendRet = nullptr;
if (AwaitSuspendCanThrow)
SuspendRet =
CGF.EmitCallOrInvoke(AwaitSuspendIntrinsic, SuspendIntrinsicCallArgs);
else
SuspendRet = CGF.EmitNounwindRuntimeCall(AwaitSuspendIntrinsic,
SuspendIntrinsicCallArgs);
assert(SuspendRet);
CGF.CurCoro.InSuspendBlock = false;
switch (SuspendReturnType) {
case CoroutineSuspendExpr::SuspendReturnType::SuspendVoid:
assert(SuspendRet->getType()->isVoidTy());
break;
case CoroutineSuspendExpr::SuspendReturnType::SuspendBool: {
assert(SuspendRet->getType()->isIntegerTy());
BasicBlock *RealSuspendBlock =
CGF.createBasicBlock(Prefix + Twine(".suspend.bool"));
CGF.Builder.CreateCondBr(SuspendRet, RealSuspendBlock, ReadyBlock);
CGF.EmitBlock(RealSuspendBlock);
break;
}
case CoroutineSuspendExpr::SuspendReturnType::SuspendHandle: {
assert(SuspendRet->getType()->isVoidTy());
break;
}
}
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 &&
StmtCanThrow(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);
CGF.EmitStmt(TryBody);
Builder.CreateFlagStore(false, Coro.ResumeEHVar);
CGF.ExitCXXTryStmt(*TryStmt);
LValueOrRValue Res;
Res.RV = RValue::getIgnored();
return Res;
}
LValueOrRValue Res;
if (forLValue)
Res.LV = CGF.EmitLValue(S.getResumeExpr());
else
Res.RV = CGF.EmitAnyExpr(S.getResumeExpr(), aggSlot, ignoreResult);
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
llvm::Function *
CodeGenFunction::generateAwaitSuspendWrapper(Twine const &CoroName,
Twine const &SuspendPointName,
CoroutineSuspendExpr const &S) {
std::string FuncName =
(CoroName + ".__await_suspend_wrapper__" + SuspendPointName).str();
ASTContext &C = getContext();
FunctionArgList args;
ImplicitParamDecl AwaiterDecl(C, C.VoidPtrTy, ImplicitParamKind::Other);
ImplicitParamDecl FrameDecl(C, C.VoidPtrTy, ImplicitParamKind::Other);
QualType ReturnTy = S.getSuspendExpr()->getType();
args.push_back(&AwaiterDecl);
args.push_back(&FrameDecl);
const CGFunctionInfo &FI =
CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
llvm::Function *Fn = llvm::Function::Create(
LTy, llvm::GlobalValue::PrivateLinkage, FuncName, &CGM.getModule());
Fn->addParamAttr(0, llvm::Attribute::AttrKind::NonNull);
Fn->addParamAttr(0, llvm::Attribute::AttrKind::NoUndef);
Fn->addParamAttr(1, llvm::Attribute::AttrKind::NoUndef);
Fn->setMustProgress();
Fn->addFnAttr(llvm::Attribute::AttrKind::AlwaysInline);
StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args);
llvm::Value *AwaiterPtr = Builder.CreateLoad(GetAddrOfLocalVar(&AwaiterDecl));
auto AwaiterLValue =
MakeNaturalAlignAddrLValue(AwaiterPtr, AwaiterDecl.getType());
CurAwaitSuspendWrapper.FramePtr =
Builder.CreateLoad(GetAddrOfLocalVar(&FrameDecl));
auto AwaiterBinder = CodeGenFunction::OpaqueValueMappingData::bind(
*this, S.getOpaqueValue(), AwaiterLValue);
auto *SuspendRet = EmitScalarExpr(S.getSuspendExpr());
auto UnbindCommonOnExit =
llvm::make_scope_exit([&] { AwaiterBinder.unbind(*this); });
if (SuspendRet != nullptr) {
Fn->addRetAttr(llvm::Attribute::AttrKind::NoUndef);
Builder.CreateStore(SuspendRet, ReturnValue);
}
CurAwaitSuspendWrapper.FramePtr = nullptr;
FinishFunction();
return Fn;
}
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(),
llvm::ConstantTokenNone::get(CoroEndFn->getContext())},
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) {}
};
}
namespace {
struct GetReturnObjectManager {
CodeGenFunction &CGF;
CGBuilderTy &Builder;
const CoroutineBodyStmt &S;
bool DirectEmit = false;
Address GroActiveFlag;
CodeGenFunction::AutoVarEmission GroEmission;
GetReturnObjectManager(CodeGenFunction &CGF, const CoroutineBodyStmt &S)
: CGF(CGF), Builder(CGF.Builder), S(S), GroActiveFlag(Address::invalid()),
GroEmission(CodeGenFunction::AutoVarEmission::invalid()) {
DirectEmit = [&]() {
auto *RVI = S.getReturnValueInit();
assert(RVI && "expected RVI");
auto GroType = RVI->getType();
return CGF.getContext().hasSameType(GroType, CGF.FnRetTy);
}();
}
void EmitGroAlloca() {
if (DirectEmit)
return;
auto *GroDeclStmt = dyn_cast_or_null<DeclStmt>(S.getResultDecl());
if (!GroDeclStmt) {
return;
}
auto *GroVarDecl = cast<VarDecl>(GroDeclStmt->getSingleDecl());
GroActiveFlag = CGF.CreateTempAlloca(Builder.getInt1Ty(), CharUnits::One(),
"gro.active");
Builder.CreateStore(Builder.getFalse(), GroActiveFlag);
GroEmission = CGF.EmitAutoVarAlloca(*GroVarDecl);
auto *GroAlloca = dyn_cast_or_null<llvm::AllocaInst>(
GroEmission.getOriginalAllocatedAddress().getPointer());
assert(GroAlloca && "expected alloca to be emitted");
GroAlloca->setMetadata(llvm::LLVMContext::MD_coro_outside_frame,
llvm::MDNode::get(CGF.CGM.getLLVMContext(), {}));
auto old_top = CGF.EHStack.stable_begin();
CGF.EmitAutoVarCleanups(GroEmission);
auto top = CGF.EHStack.stable_begin();
for (auto b = CGF.EHStack.find(top), e = CGF.EHStack.find(old_top); b != e;
b++) {
if (auto *Cleanup = dyn_cast<EHCleanupScope>(&*b)) {
assert(!Cleanup->hasActiveFlag() && "cleanup already has active flag?");
Cleanup->setActiveFlag(GroActiveFlag);
Cleanup->setTestFlagInEHCleanup();
Cleanup->setTestFlagInNormalCleanup();
}
}
}
void EmitGroInit() {
if (DirectEmit) {
assert(CGF.ReturnValue.isValid() == (bool)S.getReturnStmt());
if (CGF.ReturnValue.isValid()) {
CGF.EmitAnyExprToMem(S.getReturnValue(), CGF.ReturnValue,
S.getReturnValue()->getType().getQualifiers(),
true);
}
return;
}
if (!GroActiveFlag.isValid()) {
CGF.EmitStmt(S.getResultDecl());
return;
}
CGF.EmitAutoVarInit(GroEmission);
Builder.CreateStore(Builder.getTrue(), GroActiveFlag);
}
};
}
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.getPtrTy());
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);
emitCondLikelihoodViaExpectIntrinsic(Cond, Stmt::LH_Likely);
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;
GetReturnObjectManager GroManager(*this, S);
GroManager.EmitGroAlloca();
CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(RetBB);
{
CGDebugInfo *DI = getDebugInfo();
ParamReferenceReplacerRAII ParamReplacer(LocalDeclMap);
CodeGenFunction::RunCleanupsScope ResumeScope(*this);
EHStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, S.getDeallocate());
llvm::ArrayRef<const Stmt *> 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.emitRawPointer(*this), VoidPtrTy, "", CoroId);
CoroId->setArgOperand(1, PromiseAddrVoidPtr);
GroManager.EmitGroInit();
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(),
llvm::ConstantTokenNone::get(CoroEnd->getContext())});
if (Stmt *Ret = S.getReturnStmt()) {
if (GroManager.DirectEmit)
cast<ReturnStmt>(Ret)->setRetValue(nullptr);
EmitStmt(Ret);
}
CurFn->setPresplitCoroutine();
if (CXXRecordDecl *RD = FnRetTy->getAsCXXRecordDecl();
RD && RD->hasAttr<CoroOnlyDestroyWhenCompleteAttr>())
CurFn->setCoroDestroyOnlyWhenComplete();
}
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);
}
if (CurAwaitSuspendWrapper.FramePtr) {
return RValue::get(CurAwaitSuspendWrapper.FramePtr);
}
CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_begin "
"has been used earlier in this function");
auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getPtrTy());
return RValue::get(NullPtr);
}
case llvm::Intrinsic::coro_size: {
auto &Context = getContext();
CanQualType SizeTy = Context.getSizeType();
llvm::IntegerType *T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::coro_size, T);
return RValue::get(Builder.CreateCall(F));
}
case llvm::Intrinsic::coro_align: {
auto &Context = getContext();
CanQualType SizeTy = Context.getSizeType();
llvm::IntegerType *T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::coro_align, T);
return RValue::get(Builder.CreateCall(F));
}
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");
[[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));
if (IID == llvm::Intrinsic::coro_end)
Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
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);
}