blob: 9eb47b7bd162a608fc165edabed72031e6000ff5 [file] [log] [blame]
Gor Nishanov97e3b6d2016-10-03 22:44:48 +00001//===----- CGCoroutine.cpp - Emit LLVM Code for C++ coroutines ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation of coroutines.
11//
12//===----------------------------------------------------------------------===//
13
Gor Nishanov4c2f68f2017-05-24 02:38:26 +000014#include "CGCleanup.h"
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000015#include "CodeGenFunction.h"
Gor Nishanov5eb58582017-03-26 02:18:05 +000016#include "llvm/ADT/ScopeExit.h"
Gor Nishanov8df64e92016-10-27 16:28:31 +000017#include "clang/AST/StmtCXX.h"
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000018
19using namespace clang;
20using namespace CodeGen;
21
Gor Nishanov5eb58582017-03-26 02:18:05 +000022using llvm::Value;
23using llvm::BasicBlock;
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000024
Gor Nishanov5eb58582017-03-26 02:18:05 +000025namespace {
26enum class AwaitKind { Init, Normal, Yield, Final };
27static constexpr llvm::StringLiteral AwaitKindStr[] = {"init", "await", "yield",
28 "final"};
29}
Gor Nishanov90be1212017-03-06 21:12:54 +000030
Gor Nishanov5eb58582017-03-26 02:18:05 +000031struct clang::CodeGen::CGCoroData {
32 // What is the current await expression kind and how many
33 // await/yield expressions were encountered so far.
34 // These are used to generate pretty labels for await expressions in LLVM IR.
35 AwaitKind CurrentAwaitKind = AwaitKind::Init;
36 unsigned AwaitNum = 0;
37 unsigned YieldNum = 0;
38
39 // How many co_return statements are in the coroutine. Used to decide whether
40 // we need to add co_return; equivalent at the end of the user authored body.
41 unsigned CoreturnCount = 0;
42
43 // A branch to this block is emitted when coroutine needs to suspend.
44 llvm::BasicBlock *SuspendBB = nullptr;
45
46 // Stores the jump destination just before the coroutine memory is freed.
47 // This is the destination that every suspend point jumps to for the cleanup
48 // branch.
49 CodeGenFunction::JumpDest CleanupJD;
50
51 // Stores the jump destination just before the final suspend. The co_return
Gor Nishanov90be1212017-03-06 21:12:54 +000052 // statements jumps to this point after calling return_xxx promise member.
53 CodeGenFunction::JumpDest FinalJD;
54
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000055 // Stores the llvm.coro.id emitted in the function so that we can supply it
56 // as the first argument to coro.begin, coro.alloc and coro.free intrinsics.
57 // Note: llvm.coro.id returns a token that cannot be directly expressed in a
58 // builtin.
59 llvm::CallInst *CoroId = nullptr;
Gor Nishanov5eb58582017-03-26 02:18:05 +000060
Gor Nishanov68fe6ee2017-05-23 03:46:59 +000061 // Stores the llvm.coro.begin emitted in the function so that we can replace
62 // all coro.frame intrinsics with direct SSA value of coro.begin that returns
63 // the address of the coroutine frame of the current coroutine.
64 llvm::CallInst *CoroBegin = nullptr;
65
Gor Nishanov6c4530c2017-05-23 04:21:27 +000066 // Stores the last emitted coro.free for the deallocate expressions, we use it
67 // to wrap dealloc code with if(auto mem = coro.free) dealloc(mem).
68 llvm::CallInst *LastCoroFree = nullptr;
69
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000070 // If coro.id came from the builtin, remember the expression to give better
71 // diagnostic. If CoroIdExpr is nullptr, the coro.id was created by
72 // EmitCoroutineBody.
73 CallExpr const *CoroIdExpr = nullptr;
74};
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000075
Gor Nishanov5eb58582017-03-26 02:18:05 +000076// Defining these here allows to keep CGCoroData private to this file.
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000077clang::CodeGen::CodeGenFunction::CGCoroInfo::CGCoroInfo() {}
78CodeGenFunction::CGCoroInfo::~CGCoroInfo() {}
79
Gor Nishanov8df64e92016-10-27 16:28:31 +000080static void createCoroData(CodeGenFunction &CGF,
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000081 CodeGenFunction::CGCoroInfo &CurCoro,
Gor Nishanov8df64e92016-10-27 16:28:31 +000082 llvm::CallInst *CoroId,
83 CallExpr const *CoroIdExpr = nullptr) {
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000084 if (CurCoro.Data) {
85 if (CurCoro.Data->CoroIdExpr)
86 CGF.CGM.Error(CoroIdExpr->getLocStart(),
87 "only one __builtin_coro_id can be used in a function");
88 else if (CoroIdExpr)
89 CGF.CGM.Error(CoroIdExpr->getLocStart(),
90 "__builtin_coro_id shall not be used in a C++ coroutine");
91 else
92 llvm_unreachable("EmitCoroutineBodyStatement called twice?");
93
Gor Nishanov8df64e92016-10-27 16:28:31 +000094 return;
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000095 }
96
97 CurCoro.Data = std::unique_ptr<CGCoroData>(new CGCoroData);
98 CurCoro.Data->CoroId = CoroId;
99 CurCoro.Data->CoroIdExpr = CoroIdExpr;
Gor Nishanov8df64e92016-10-27 16:28:31 +0000100}
101
Gor Nishanov5eb58582017-03-26 02:18:05 +0000102// Synthesize a pretty name for a suspend point.
103static SmallString<32> buildSuspendPrefixStr(CGCoroData &Coro, AwaitKind Kind) {
104 unsigned No = 0;
105 switch (Kind) {
106 case AwaitKind::Init:
107 case AwaitKind::Final:
108 break;
109 case AwaitKind::Normal:
110 No = ++Coro.AwaitNum;
111 break;
112 case AwaitKind::Yield:
113 No = ++Coro.YieldNum;
114 break;
115 }
116 SmallString<32> Prefix(AwaitKindStr[static_cast<unsigned>(Kind)]);
117 if (No > 1) {
118 Twine(No).toVector(Prefix);
119 }
120 return Prefix;
121}
122
123// Emit suspend expression which roughly looks like:
124//
125// auto && x = CommonExpr();
126// if (!x.await_ready()) {
127// llvm_coro_save();
128// x.await_suspend(...); (*)
129// llvm_coro_suspend(); (**)
130// }
131// x.await_resume();
132//
133// where the result of the entire expression is the result of x.await_resume()
134//
135// (*) If x.await_suspend return type is bool, it allows to veto a suspend:
136// if (x.await_suspend(...))
137// llvm_coro_suspend();
138//
139// (**) llvm_coro_suspend() encodes three possible continuations as
140// a switch instruction:
141//
142// %where-to = call i8 @llvm.coro.suspend(...)
143// switch i8 %where-to, label %coro.ret [ ; jump to epilogue to suspend
144// i8 0, label %yield.ready ; go here when resumed
145// i8 1, label %yield.cleanup ; go here when destroyed
146// ]
147//
148// See llvm's docs/Coroutines.rst for more details.
149//
150static RValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro,
151 CoroutineSuspendExpr const &S,
152 AwaitKind Kind, AggValueSlot aggSlot,
153 bool ignoreResult) {
154 auto *E = S.getCommonExpr();
Gor Nishanove4f15a22017-05-23 05:25:31 +0000155
156 // FIXME: rsmith 5/22/2017. Does it still make sense for us to have a
157 // UO_Coawait at all? As I recall, the only purpose it ever had was to
158 // represent a dependent co_await expression that couldn't yet be resolved to
159 // a CoawaitExpr. But now we have (and need!) a separate DependentCoawaitExpr
160 // node to store unqualified lookup results, it seems that the UnaryOperator
161 // portion of the representation serves no purpose (and as seen in this patch,
162 // it's getting in the way). Can we remove it?
163
164 // Skip passthrough operator co_await (present when awaiting on an LValue).
165 if (auto *UO = dyn_cast<UnaryOperator>(E))
166 if (UO->getOpcode() == UO_Coawait)
167 E = UO->getSubExpr();
168
Gor Nishanov5eb58582017-03-26 02:18:05 +0000169 auto Binder =
170 CodeGenFunction::OpaqueValueMappingData::bind(CGF, S.getOpaqueValue(), E);
171 auto UnbindOnExit = llvm::make_scope_exit([&] { Binder.unbind(CGF); });
172
173 auto Prefix = buildSuspendPrefixStr(Coro, Kind);
174 BasicBlock *ReadyBlock = CGF.createBasicBlock(Prefix + Twine(".ready"));
175 BasicBlock *SuspendBlock = CGF.createBasicBlock(Prefix + Twine(".suspend"));
176 BasicBlock *CleanupBlock = CGF.createBasicBlock(Prefix + Twine(".cleanup"));
177
178 // If expression is ready, no need to suspend.
179 CGF.EmitBranchOnBoolExpr(S.getReadyExpr(), ReadyBlock, SuspendBlock, 0);
180
181 // Otherwise, emit suspend logic.
182 CGF.EmitBlock(SuspendBlock);
183
184 auto &Builder = CGF.Builder;
185 llvm::Function *CoroSave = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_save);
186 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.CGM.Int8PtrTy);
187 auto *SaveCall = Builder.CreateCall(CoroSave, {NullPtr});
188
189 auto *SuspendRet = CGF.EmitScalarExpr(S.getSuspendExpr());
190 if (SuspendRet != nullptr) {
191 // Veto suspension if requested by bool returning await_suspend.
192 assert(SuspendRet->getType()->isIntegerTy(1) &&
193 "Sema should have already checked that it is void or bool");
194 BasicBlock *RealSuspendBlock =
195 CGF.createBasicBlock(Prefix + Twine(".suspend.bool"));
196 CGF.Builder.CreateCondBr(SuspendRet, RealSuspendBlock, ReadyBlock);
197 SuspendBlock = RealSuspendBlock;
198 CGF.EmitBlock(RealSuspendBlock);
199 }
200
201 // Emit the suspend point.
202 const bool IsFinalSuspend = (Kind == AwaitKind::Final);
203 llvm::Function *CoroSuspend =
204 CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_suspend);
205 auto *SuspendResult = Builder.CreateCall(
206 CoroSuspend, {SaveCall, Builder.getInt1(IsFinalSuspend)});
207
208 // Create a switch capturing three possible continuations.
209 auto *Switch = Builder.CreateSwitch(SuspendResult, Coro.SuspendBB, 2);
210 Switch->addCase(Builder.getInt8(0), ReadyBlock);
211 Switch->addCase(Builder.getInt8(1), CleanupBlock);
212
213 // Emit cleanup for this suspend point.
214 CGF.EmitBlock(CleanupBlock);
215 CGF.EmitBranchThroughCleanup(Coro.CleanupJD);
216
217 // Emit await_resume expression.
218 CGF.EmitBlock(ReadyBlock);
219 return CGF.EmitAnyExpr(S.getResumeExpr(), aggSlot, ignoreResult);
220}
221
222RValue CodeGenFunction::EmitCoawaitExpr(const CoawaitExpr &E,
223 AggValueSlot aggSlot,
224 bool ignoreResult) {
225 return emitSuspendExpression(*this, *CurCoro.Data, E,
226 CurCoro.Data->CurrentAwaitKind, aggSlot,
227 ignoreResult);
228}
229RValue CodeGenFunction::EmitCoyieldExpr(const CoyieldExpr &E,
230 AggValueSlot aggSlot,
231 bool ignoreResult) {
232 return emitSuspendExpression(*this, *CurCoro.Data, E, AwaitKind::Yield,
233 aggSlot, ignoreResult);
234}
235
Gor Nishanov90be1212017-03-06 21:12:54 +0000236void CodeGenFunction::EmitCoreturnStmt(CoreturnStmt const &S) {
237 ++CurCoro.Data->CoreturnCount;
238 EmitStmt(S.getPromiseCall());
239 EmitBranchThroughCleanup(CurCoro.Data->FinalJD);
240}
241
Gor Nishanov818a7762017-04-05 04:55:03 +0000242// For WinEH exception representation backend need to know what funclet coro.end
243// belongs to. That information is passed in a funclet bundle.
244static SmallVector<llvm::OperandBundleDef, 1>
245getBundlesForCoroEnd(CodeGenFunction &CGF) {
246 SmallVector<llvm::OperandBundleDef, 1> BundleList;
247
248 if (llvm::Instruction *EHPad = CGF.CurrentFuncletPad)
249 BundleList.emplace_back("funclet", EHPad);
250
251 return BundleList;
252}
253
254namespace {
255// We will insert coro.end to cut any of the destructors for objects that
256// do not need to be destroyed once the coroutine is resumed.
257// See llvm/docs/Coroutines.rst for more details about coro.end.
258struct CallCoroEnd final : public EHScopeStack::Cleanup {
259 void Emit(CodeGenFunction &CGF, Flags flags) override {
260 auto &CGM = CGF.CGM;
261 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
262 llvm::Function *CoroEndFn = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
263 // See if we have a funclet bundle to associate coro.end with. (WinEH)
264 auto Bundles = getBundlesForCoroEnd(CGF);
265 auto *CoroEnd = CGF.Builder.CreateCall(
266 CoroEndFn, {NullPtr, CGF.Builder.getTrue()}, Bundles);
267 if (Bundles.empty()) {
268 // Otherwise, (landingpad model), create a conditional branch that leads
269 // either to a cleanup block or a block with EH resume instruction.
270 auto *ResumeBB = CGF.getEHResumeBlock(/*cleanup=*/true);
271 auto *CleanupContBB = CGF.createBasicBlock("cleanup.cont");
272 CGF.Builder.CreateCondBr(CoroEnd, ResumeBB, CleanupContBB);
273 CGF.EmitBlock(CleanupContBB);
274 }
275 }
276};
277}
278
Gor Nishanov63b6df42017-04-01 00:22:47 +0000279namespace {
280// Make sure to call coro.delete on scope exit.
281struct CallCoroDelete final : public EHScopeStack::Cleanup {
282 Stmt *Deallocate;
283
Gor Nishanov6c4530c2017-05-23 04:21:27 +0000284 // Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;"
285
286 // Note: That deallocation will be emitted twice: once for a normal exit and
287 // once for exceptional exit. This usage is safe because Deallocate does not
288 // contain any declarations. The SubStmtBuilder::makeNewAndDeleteExpr()
289 // builds a single call to a deallocation function which is safe to emit
290 // multiple times.
Gor Nishanov63b6df42017-04-01 00:22:47 +0000291 void Emit(CodeGenFunction &CGF, Flags) override {
Gor Nishanov6c4530c2017-05-23 04:21:27 +0000292 // Remember the current point, as we are going to emit deallocation code
293 // first to get to coro.free instruction that is an argument to a delete
294 // call.
295 BasicBlock *SaveInsertBlock = CGF.Builder.GetInsertBlock();
296
297 auto *FreeBB = CGF.createBasicBlock("coro.free");
298 CGF.EmitBlock(FreeBB);
Gor Nishanov63b6df42017-04-01 00:22:47 +0000299 CGF.EmitStmt(Deallocate);
Gor Nishanov6c4530c2017-05-23 04:21:27 +0000300
301 auto *AfterFreeBB = CGF.createBasicBlock("after.coro.free");
302 CGF.EmitBlock(AfterFreeBB);
303
304 // We should have captured coro.free from the emission of deallocate.
305 auto *CoroFree = CGF.CurCoro.Data->LastCoroFree;
306 if (!CoroFree) {
307 CGF.CGM.Error(Deallocate->getLocStart(),
308 "Deallocation expressoin does not refer to coro.free");
309 return;
310 }
311
312 // Get back to the block we were originally and move coro.free there.
313 auto *InsertPt = SaveInsertBlock->getTerminator();
314 CoroFree->moveBefore(InsertPt);
315 CGF.Builder.SetInsertPoint(InsertPt);
316
317 // Add if (auto *mem = coro.free) Deallocate;
318 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
319 auto *Cond = CGF.Builder.CreateICmpNE(CoroFree, NullPtr);
320 CGF.Builder.CreateCondBr(Cond, FreeBB, AfterFreeBB);
321
322 // No longer need old terminator.
323 InsertPt->eraseFromParent();
324 CGF.Builder.SetInsertPoint(AfterFreeBB);
Gor Nishanov63b6df42017-04-01 00:22:47 +0000325 }
326 explicit CallCoroDelete(Stmt *DeallocStmt) : Deallocate(DeallocStmt) {}
327};
328}
329
Gor Nishanov4c2f68f2017-05-24 02:38:26 +0000330namespace {
331struct GetReturnObjectManager {
332 CodeGenFunction &CGF;
333 CGBuilderTy &Builder;
334 const CoroutineBodyStmt &S;
335
336 Address GroActiveFlag;
337 CodeGenFunction::AutoVarEmission GroEmission;
338
339 GetReturnObjectManager(CodeGenFunction &CGF, const CoroutineBodyStmt &S)
340 : CGF(CGF), Builder(CGF.Builder), S(S), GroActiveFlag(Address::invalid()),
341 GroEmission(CodeGenFunction::AutoVarEmission::invalid()) {}
342
343 // The gro variable has to outlive coroutine frame and coroutine promise, but,
344 // it can only be initialized after coroutine promise was created, thus, we
345 // split its emission in two parts. EmitGroAlloca emits an alloca and sets up
346 // cleanups. Later when coroutine promise is available we initialize the gro
347 // and sets the flag that the cleanup is now active.
348
349 void EmitGroAlloca() {
350 auto *GroDeclStmt = dyn_cast<DeclStmt>(S.getResultDecl());
351 if (!GroDeclStmt) {
352 // If get_return_object returns void, no need to do an alloca.
353 return;
354 }
355
356 auto *GroVarDecl = cast<VarDecl>(GroDeclStmt->getSingleDecl());
357
358 // Set GRO flag that it is not initialized yet
359 GroActiveFlag =
360 CGF.CreateTempAlloca(Builder.getInt1Ty(), CharUnits::One(), "gro.active");
361 Builder.CreateStore(Builder.getFalse(), GroActiveFlag);
362
363 GroEmission = CGF.EmitAutoVarAlloca(*GroVarDecl);
364
365 // Remember the top of EHStack before emitting the cleanup.
366 auto old_top = CGF.EHStack.stable_begin();
367 CGF.EmitAutoVarCleanups(GroEmission);
368 auto top = CGF.EHStack.stable_begin();
369
370 // Make the cleanup conditional on gro.active
371 for (auto b = CGF.EHStack.find(top), e = CGF.EHStack.find(old_top);
372 b != e; b++) {
373 if (auto *Cleanup = dyn_cast<EHCleanupScope>(&*b)) {
374 assert(!Cleanup->hasActiveFlag() && "cleanup already has active flag?");
375 Cleanup->setActiveFlag(GroActiveFlag);
376 Cleanup->setTestFlagInEHCleanup();
377 Cleanup->setTestFlagInNormalCleanup();
378 }
379 }
380 }
381
382 void EmitGroInit() {
383 if (!GroActiveFlag.isValid()) {
384 // No Gro variable was allocated. Simply emit the call to
385 // get_return_object.
386 CGF.EmitStmt(S.getResultDecl());
387 return;
388 }
389
390 CGF.EmitAutoVarInit(GroEmission);
391 Builder.CreateStore(Builder.getTrue(), GroActiveFlag);
392 }
393};
394}
395
Gor Nishanov5b050e42017-05-22 22:33:17 +0000396static void emitBodyAndFallthrough(CodeGenFunction &CGF,
397 const CoroutineBodyStmt &S, Stmt *Body) {
398 CGF.EmitStmt(Body);
399 const bool CanFallthrough = CGF.Builder.GetInsertBlock();
400 if (CanFallthrough)
401 if (Stmt *OnFallthrough = S.getFallthroughHandler())
402 CGF.EmitStmt(OnFallthrough);
403}
404
Gor Nishanov8df64e92016-10-27 16:28:31 +0000405void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt &S) {
406 auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
407 auto &TI = CGM.getContext().getTargetInfo();
408 unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();
409
Gor Nishanovaa6e9a92017-05-23 01:13:17 +0000410 auto *EntryBB = Builder.GetInsertBlock();
411 auto *AllocBB = createBasicBlock("coro.alloc");
412 auto *InitBB = createBasicBlock("coro.init");
Gor Nishanov90be1212017-03-06 21:12:54 +0000413 auto *FinalBB = createBasicBlock("coro.final");
Gor Nishanov5eb58582017-03-26 02:18:05 +0000414 auto *RetBB = createBasicBlock("coro.ret");
Gor Nishanov90be1212017-03-06 21:12:54 +0000415
Gor Nishanov8df64e92016-10-27 16:28:31 +0000416 auto *CoroId = Builder.CreateCall(
417 CGM.getIntrinsic(llvm::Intrinsic::coro_id),
418 {Builder.getInt32(NewAlign), NullPtr, NullPtr, NullPtr});
419 createCoroData(*this, CurCoro, CoroId);
Gor Nishanov5eb58582017-03-26 02:18:05 +0000420 CurCoro.Data->SuspendBB = RetBB;
Gor Nishanov8df64e92016-10-27 16:28:31 +0000421
Gor Nishanovaa6e9a92017-05-23 01:13:17 +0000422 // Backend is allowed to elide memory allocations, to help it, emit
423 // auto mem = coro.alloc() ? 0 : ... allocation code ...;
424 auto *CoroAlloc = Builder.CreateCall(
425 CGM.getIntrinsic(llvm::Intrinsic::coro_alloc), {CoroId});
426
427 Builder.CreateCondBr(CoroAlloc, AllocBB, InitBB);
428
429 EmitBlock(AllocBB);
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000430 auto *AllocateCall = EmitScalarExpr(S.getAllocate());
Gor Nishanovaa6e9a92017-05-23 01:13:17 +0000431 auto *AllocOrInvokeContBB = Builder.GetInsertBlock();
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000432
433 // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
434 if (auto *RetOnAllocFailure = S.getReturnStmtOnAllocFailure()) {
435 auto *RetOnFailureBB = createBasicBlock("coro.ret.on.failure");
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000436
437 // See if allocation was successful.
438 auto *NullPtr = llvm::ConstantPointerNull::get(Int8PtrTy);
439 auto *Cond = Builder.CreateICmpNE(AllocateCall, NullPtr);
440 Builder.CreateCondBr(Cond, InitBB, RetOnFailureBB);
441
442 // If not, return OnAllocFailure object.
443 EmitBlock(RetOnFailureBB);
444 EmitStmt(RetOnAllocFailure);
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000445 }
Gor Nishanovaa6e9a92017-05-23 01:13:17 +0000446 else {
447 Builder.CreateBr(InitBB);
448 }
449
450 EmitBlock(InitBB);
451
452 // Pass the result of the allocation to coro.begin.
453 auto *Phi = Builder.CreatePHI(VoidPtrTy, 2);
454 Phi->addIncoming(NullPtr, EntryBB);
455 Phi->addIncoming(AllocateCall, AllocOrInvokeContBB);
Gor Nishanov68fe6ee2017-05-23 03:46:59 +0000456 auto *CoroBegin = Builder.CreateCall(
Gor Nishanovaa6e9a92017-05-23 01:13:17 +0000457 CGM.getIntrinsic(llvm::Intrinsic::coro_begin), {CoroId, Phi});
Gor Nishanov68fe6ee2017-05-23 03:46:59 +0000458 CurCoro.Data->CoroBegin = CoroBegin;
Gor Nishanov90be1212017-03-06 21:12:54 +0000459
Gor Nishanov4c2f68f2017-05-24 02:38:26 +0000460 GetReturnObjectManager GroManager(*this, S);
461 GroManager.EmitGroAlloca();
462
Gor Nishanov5eb58582017-03-26 02:18:05 +0000463 CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(RetBB);
Gor Nishanov63b6df42017-04-01 00:22:47 +0000464 {
465 CodeGenFunction::RunCleanupsScope ResumeScope(*this);
466 EHStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, S.getDeallocate());
Gor Nishanov90be1212017-03-06 21:12:54 +0000467
Gor Nishanov63b6df42017-04-01 00:22:47 +0000468 EmitStmt(S.getPromiseDeclStmt());
Gor Nishanov90be1212017-03-06 21:12:54 +0000469
Gor Nishanov4c2f68f2017-05-24 02:38:26 +0000470 // Now we have the promise, initialize the GRO
471 GroManager.EmitGroInit();
Gor Nishanov818a7762017-04-05 04:55:03 +0000472 EHStack.pushCleanup<CallCoroEnd>(EHCleanup);
473
Gor Nishanov63b6df42017-04-01 00:22:47 +0000474 CurCoro.Data->FinalJD = getJumpDestInCurrentScope(FinalBB);
Gor Nishanov90be1212017-03-06 21:12:54 +0000475
Gor Nishanov5efc6182017-05-23 05:04:01 +0000476 // FIXME: Emit param moves.
477
478 CurCoro.Data->CurrentAwaitKind = AwaitKind::Init;
479 EmitStmt(S.getInitSuspendStmt());
Gor Nishanov63b6df42017-04-01 00:22:47 +0000480
481 CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal;
Gor Nishanov5b050e42017-05-22 22:33:17 +0000482
483 if (auto *OnException = S.getExceptionHandler()) {
484 auto Loc = S.getLocStart();
485 CXXCatchStmt Catch(Loc, /*exDecl=*/nullptr, OnException);
486 auto *TryStmt = CXXTryStmt::Create(getContext(), Loc, S.getBody(), &Catch);
487
488 EnterCXXTryStmt(*TryStmt);
489 emitBodyAndFallthrough(*this, S, TryStmt->getTryBlock());
490 ExitCXXTryStmt(*TryStmt);
491 }
492 else {
493 emitBodyAndFallthrough(*this, S, S.getBody());
494 }
Gor Nishanov63b6df42017-04-01 00:22:47 +0000495
496 // See if we need to generate final suspend.
497 const bool CanFallthrough = Builder.GetInsertBlock();
498 const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0;
499 if (CanFallthrough || HasCoreturns) {
500 EmitBlock(FinalBB);
Gor Nishanov5efc6182017-05-23 05:04:01 +0000501 CurCoro.Data->CurrentAwaitKind = AwaitKind::Final;
502 EmitStmt(S.getFinalSuspendStmt());
Gor Nishanov63b6df42017-04-01 00:22:47 +0000503 }
Gor Nishanovdb615dd2017-05-24 01:54:37 +0000504 else {
505 // We don't need FinalBB. Emit it to make sure the block is deleted.
506 EmitBlock(FinalBB, /*IsFinished=*/true);
507 }
Gor Nishanov90be1212017-03-06 21:12:54 +0000508 }
Gor Nishanov90be1212017-03-06 21:12:54 +0000509
Gor Nishanov5eb58582017-03-26 02:18:05 +0000510 EmitBlock(RetBB);
Gor Nishanov6a470682017-05-22 20:22:23 +0000511 // Emit coro.end before getReturnStmt (and parameter destructors), since
512 // resume and destroy parts of the coroutine should not include them.
Gor Nishanov818a7762017-04-05 04:55:03 +0000513 llvm::Function *CoroEnd = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
514 Builder.CreateCall(CoroEnd, {NullPtr, Builder.getFalse()});
Gor Nishanov5eb58582017-03-26 02:18:05 +0000515
Gor Nishanov6a470682017-05-22 20:22:23 +0000516 if (Stmt *Ret = S.getReturnStmt())
517 EmitStmt(Ret);
Gor Nishanov97e3b6d2016-10-03 22:44:48 +0000518}
519
520// Emit coroutine intrinsic and patch up arguments of the token type.
521RValue CodeGenFunction::EmitCoroutineIntrinsic(const CallExpr *E,
522 unsigned int IID) {
523 SmallVector<llvm::Value *, 8> Args;
524 switch (IID) {
525 default:
526 break;
Gor Nishanov68fe6ee2017-05-23 03:46:59 +0000527 // The coro.frame builtin is replaced with an SSA value of the coro.begin
528 // intrinsic.
529 case llvm::Intrinsic::coro_frame: {
530 if (CurCoro.Data && CurCoro.Data->CoroBegin) {
531 return RValue::get(CurCoro.Data->CoroBegin);
532 }
533 CGM.Error(E->getLocStart(), "this builtin expect that __builtin_coro_begin "
534 "has been used earlier in this function");
535 auto NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
536 return RValue::get(NullPtr);
537 }
Gor Nishanov97e3b6d2016-10-03 22:44:48 +0000538 // The following three intrinsics take a token parameter referring to a token
539 // returned by earlier call to @llvm.coro.id. Since we cannot represent it in
540 // builtins, we patch it up here.
541 case llvm::Intrinsic::coro_alloc:
542 case llvm::Intrinsic::coro_begin:
543 case llvm::Intrinsic::coro_free: {
544 if (CurCoro.Data && CurCoro.Data->CoroId) {
545 Args.push_back(CurCoro.Data->CoroId);
546 break;
547 }
548 CGM.Error(E->getLocStart(), "this builtin expect that __builtin_coro_id has"
549 " been used earlier in this function");
550 // Fallthrough to the next case to add TokenNone as the first argument.
551 }
552 // @llvm.coro.suspend takes a token parameter. Add token 'none' as the first
553 // argument.
554 case llvm::Intrinsic::coro_suspend:
555 Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
556 break;
557 }
558 for (auto &Arg : E->arguments())
559 Args.push_back(EmitScalarExpr(Arg));
560
561 llvm::Value *F = CGM.getIntrinsic(IID);
562 llvm::CallInst *Call = Builder.CreateCall(F, Args);
563
Gor Nishanov6c4530c2017-05-23 04:21:27 +0000564 // Note: The following code is to enable to emit coro.id and coro.begin by
Gor Nishanov68fe6ee2017-05-23 03:46:59 +0000565 // hand to experiment with coroutines in C.
Gor Nishanov97e3b6d2016-10-03 22:44:48 +0000566 // If we see @llvm.coro.id remember it in the CoroData. We will update
567 // coro.alloc, coro.begin and coro.free intrinsics to refer to it.
568 if (IID == llvm::Intrinsic::coro_id) {
569 createCoroData(*this, CurCoro, Call, E);
570 }
Gor Nishanov68fe6ee2017-05-23 03:46:59 +0000571 else if (IID == llvm::Intrinsic::coro_begin) {
572 if (CurCoro.Data)
573 CurCoro.Data->CoroBegin = Call;
574 }
Gor Nishanov6c4530c2017-05-23 04:21:27 +0000575 else if (IID == llvm::Intrinsic::coro_free) {
576 // Remember the last coro_free as we need it to build the conditional
577 // deletion of the coroutine frame.
578 if (CurCoro.Data)
579 CurCoro.Data->LastCoroFree = Call;
580 } return RValue::get(Call);
Gor Nishanov97e3b6d2016-10-03 22:44:48 +0000581}