1 //===----- 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 
14 #include "CodeGenFunction.h"
15 #include "llvm/ADT/ScopeExit.h"
16 #include "clang/AST/StmtCXX.h"
17 
18 using namespace clang;
19 using namespace CodeGen;
20 
21 using llvm::Value;
22 using llvm::BasicBlock;
23 
24 namespace {
25 enum class AwaitKind { Init, Normal, Yield, Final };
26 static constexpr llvm::StringLiteral AwaitKindStr[] = {"init", "await", "yield",
27                                                        "final"};
28 }
29 
30 struct clang::CodeGen::CGCoroData {
31   // What is the current await expression kind and how many
32   // await/yield expressions were encountered so far.
33   // These are used to generate pretty labels for await expressions in LLVM IR.
34   AwaitKind CurrentAwaitKind = AwaitKind::Init;
35   unsigned AwaitNum = 0;
36   unsigned YieldNum = 0;
37 
38   // How many co_return statements are in the coroutine. Used to decide whether
39   // we need to add co_return; equivalent at the end of the user authored body.
40   unsigned CoreturnCount = 0;
41 
42   // A branch to this block is emitted when coroutine needs to suspend.
43   llvm::BasicBlock *SuspendBB = nullptr;
44 
45   // Stores the jump destination just before the coroutine memory is freed.
46   // This is the destination that every suspend point jumps to for the cleanup
47   // branch.
48   CodeGenFunction::JumpDest CleanupJD;
49 
50   // Stores the jump destination just before the final suspend. The co_return
51   // statements jumps to this point after calling return_xxx promise member.
52   CodeGenFunction::JumpDest FinalJD;
53 
54   // Stores the llvm.coro.id emitted in the function so that we can supply it
55   // as the first argument to coro.begin, coro.alloc and coro.free intrinsics.
56   // Note: llvm.coro.id returns a token that cannot be directly expressed in a
57   // builtin.
58   llvm::CallInst *CoroId = nullptr;
59 
60   // Stores the llvm.coro.begin emitted in the function so that we can replace
61   // all coro.frame intrinsics with direct SSA value of coro.begin that returns
62   // the address of the coroutine frame of the current coroutine.
63   llvm::CallInst *CoroBegin = nullptr;
64 
65   // Stores the last emitted coro.free for the deallocate expressions, we use it
66   // to wrap dealloc code with if(auto mem = coro.free) dealloc(mem).
67   llvm::CallInst *LastCoroFree = nullptr;
68 
69   // If coro.id came from the builtin, remember the expression to give better
70   // diagnostic. If CoroIdExpr is nullptr, the coro.id was created by
71   // EmitCoroutineBody.
72   CallExpr const *CoroIdExpr = nullptr;
73 };
74 
75 // Defining these here allows to keep CGCoroData private to this file.
76 clang::CodeGen::CodeGenFunction::CGCoroInfo::CGCoroInfo() {}
77 CodeGenFunction::CGCoroInfo::~CGCoroInfo() {}
78 
79 static void createCoroData(CodeGenFunction &CGF,
80                            CodeGenFunction::CGCoroInfo &CurCoro,
81                            llvm::CallInst *CoroId,
82                            CallExpr const *CoroIdExpr = nullptr) {
83   if (CurCoro.Data) {
84     if (CurCoro.Data->CoroIdExpr)
85       CGF.CGM.Error(CoroIdExpr->getLocStart(),
86                     "only one __builtin_coro_id can be used in a function");
87     else if (CoroIdExpr)
88       CGF.CGM.Error(CoroIdExpr->getLocStart(),
89                     "__builtin_coro_id shall not be used in a C++ coroutine");
90     else
91       llvm_unreachable("EmitCoroutineBodyStatement called twice?");
92 
93     return;
94   }
95 
96   CurCoro.Data = std::unique_ptr<CGCoroData>(new CGCoroData);
97   CurCoro.Data->CoroId = CoroId;
98   CurCoro.Data->CoroIdExpr = CoroIdExpr;
99 }
100 
101 // Synthesize a pretty name for a suspend point.
102 static SmallString<32> buildSuspendPrefixStr(CGCoroData &Coro, AwaitKind Kind) {
103   unsigned No = 0;
104   switch (Kind) {
105   case AwaitKind::Init:
106   case AwaitKind::Final:
107     break;
108   case AwaitKind::Normal:
109     No = ++Coro.AwaitNum;
110     break;
111   case AwaitKind::Yield:
112     No = ++Coro.YieldNum;
113     break;
114   }
115   SmallString<32> Prefix(AwaitKindStr[static_cast<unsigned>(Kind)]);
116   if (No > 1) {
117     Twine(No).toVector(Prefix);
118   }
119   return Prefix;
120 }
121 
122 // Emit suspend expression which roughly looks like:
123 //
124 //   auto && x = CommonExpr();
125 //   if (!x.await_ready()) {
126 //      llvm_coro_save();
127 //      x.await_suspend(...);     (*)
128 //      llvm_coro_suspend(); (**)
129 //   }
130 //   x.await_resume();
131 //
132 // where the result of the entire expression is the result of x.await_resume()
133 //
134 //   (*) If x.await_suspend return type is bool, it allows to veto a suspend:
135 //      if (x.await_suspend(...))
136 //        llvm_coro_suspend();
137 //
138 //  (**) llvm_coro_suspend() encodes three possible continuations as
139 //       a switch instruction:
140 //
141 //  %where-to = call i8 @llvm.coro.suspend(...)
142 //  switch i8 %where-to, label %coro.ret [ ; jump to epilogue to suspend
143 //    i8 0, label %yield.ready   ; go here when resumed
144 //    i8 1, label %yield.cleanup ; go here when destroyed
145 //  ]
146 //
147 //  See llvm's docs/Coroutines.rst for more details.
148 //
149 static RValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro,
150                                     CoroutineSuspendExpr const &S,
151                                     AwaitKind Kind, AggValueSlot aggSlot,
152                                     bool ignoreResult) {
153   auto *E = S.getCommonExpr();
154 
155   // FIXME: rsmith 5/22/2017. Does it still make sense for us to have a
156   // UO_Coawait at all? As I recall, the only purpose it ever had was to
157   // represent a dependent co_await expression that couldn't yet be resolved to
158   // a CoawaitExpr. But now we have (and need!) a separate DependentCoawaitExpr
159   // node to store unqualified lookup results, it seems that the UnaryOperator
160   // portion of the representation serves no purpose (and as seen in this patch,
161   // it's getting in the way). Can we remove it?
162 
163   // Skip passthrough operator co_await (present when awaiting on an LValue).
164   if (auto *UO = dyn_cast<UnaryOperator>(E))
165     if (UO->getOpcode() == UO_Coawait)
166       E = UO->getSubExpr();
167 
168   auto Binder =
169       CodeGenFunction::OpaqueValueMappingData::bind(CGF, S.getOpaqueValue(), E);
170   auto UnbindOnExit = llvm::make_scope_exit([&] { Binder.unbind(CGF); });
171 
172   auto Prefix = buildSuspendPrefixStr(Coro, Kind);
173   BasicBlock *ReadyBlock = CGF.createBasicBlock(Prefix + Twine(".ready"));
174   BasicBlock *SuspendBlock = CGF.createBasicBlock(Prefix + Twine(".suspend"));
175   BasicBlock *CleanupBlock = CGF.createBasicBlock(Prefix + Twine(".cleanup"));
176 
177   // If expression is ready, no need to suspend.
178   CGF.EmitBranchOnBoolExpr(S.getReadyExpr(), ReadyBlock, SuspendBlock, 0);
179 
180   // Otherwise, emit suspend logic.
181   CGF.EmitBlock(SuspendBlock);
182 
183   auto &Builder = CGF.Builder;
184   llvm::Function *CoroSave = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_save);
185   auto *NullPtr = llvm::ConstantPointerNull::get(CGF.CGM.Int8PtrTy);
186   auto *SaveCall = Builder.CreateCall(CoroSave, {NullPtr});
187 
188   auto *SuspendRet = CGF.EmitScalarExpr(S.getSuspendExpr());
189   if (SuspendRet != nullptr) {
190     // Veto suspension if requested by bool returning await_suspend.
191     assert(SuspendRet->getType()->isIntegerTy(1) &&
192            "Sema should have already checked that it is void or bool");
193     BasicBlock *RealSuspendBlock =
194         CGF.createBasicBlock(Prefix + Twine(".suspend.bool"));
195     CGF.Builder.CreateCondBr(SuspendRet, RealSuspendBlock, ReadyBlock);
196     SuspendBlock = RealSuspendBlock;
197     CGF.EmitBlock(RealSuspendBlock);
198   }
199 
200   // Emit the suspend point.
201   const bool IsFinalSuspend = (Kind == AwaitKind::Final);
202   llvm::Function *CoroSuspend =
203       CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_suspend);
204   auto *SuspendResult = Builder.CreateCall(
205       CoroSuspend, {SaveCall, Builder.getInt1(IsFinalSuspend)});
206 
207   // Create a switch capturing three possible continuations.
208   auto *Switch = Builder.CreateSwitch(SuspendResult, Coro.SuspendBB, 2);
209   Switch->addCase(Builder.getInt8(0), ReadyBlock);
210   Switch->addCase(Builder.getInt8(1), CleanupBlock);
211 
212   // Emit cleanup for this suspend point.
213   CGF.EmitBlock(CleanupBlock);
214   CGF.EmitBranchThroughCleanup(Coro.CleanupJD);
215 
216   // Emit await_resume expression.
217   CGF.EmitBlock(ReadyBlock);
218   return CGF.EmitAnyExpr(S.getResumeExpr(), aggSlot, ignoreResult);
219 }
220 
221 RValue CodeGenFunction::EmitCoawaitExpr(const CoawaitExpr &E,
222                                         AggValueSlot aggSlot,
223                                         bool ignoreResult) {
224   return emitSuspendExpression(*this, *CurCoro.Data, E,
225                                CurCoro.Data->CurrentAwaitKind, aggSlot,
226                                ignoreResult);
227 }
228 RValue CodeGenFunction::EmitCoyieldExpr(const CoyieldExpr &E,
229                                         AggValueSlot aggSlot,
230                                         bool ignoreResult) {
231   return emitSuspendExpression(*this, *CurCoro.Data, E, AwaitKind::Yield,
232                                aggSlot, ignoreResult);
233 }
234 
235 void CodeGenFunction::EmitCoreturnStmt(CoreturnStmt const &S) {
236   ++CurCoro.Data->CoreturnCount;
237   EmitStmt(S.getPromiseCall());
238   EmitBranchThroughCleanup(CurCoro.Data->FinalJD);
239 }
240 
241 // For WinEH exception representation backend need to know what funclet coro.end
242 // belongs to. That information is passed in a funclet bundle.
243 static SmallVector<llvm::OperandBundleDef, 1>
244 getBundlesForCoroEnd(CodeGenFunction &CGF) {
245   SmallVector<llvm::OperandBundleDef, 1> BundleList;
246 
247   if (llvm::Instruction *EHPad = CGF.CurrentFuncletPad)
248     BundleList.emplace_back("funclet", EHPad);
249 
250   return BundleList;
251 }
252 
253 namespace {
254 // We will insert coro.end to cut any of the destructors for objects that
255 // do not need to be destroyed once the coroutine is resumed.
256 // See llvm/docs/Coroutines.rst for more details about coro.end.
257 struct CallCoroEnd final : public EHScopeStack::Cleanup {
258   void Emit(CodeGenFunction &CGF, Flags flags) override {
259     auto &CGM = CGF.CGM;
260     auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
261     llvm::Function *CoroEndFn = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
262     // See if we have a funclet bundle to associate coro.end with. (WinEH)
263     auto Bundles = getBundlesForCoroEnd(CGF);
264     auto *CoroEnd = CGF.Builder.CreateCall(
265         CoroEndFn, {NullPtr, CGF.Builder.getTrue()}, Bundles);
266     if (Bundles.empty()) {
267       // Otherwise, (landingpad model), create a conditional branch that leads
268       // either to a cleanup block or a block with EH resume instruction.
269       auto *ResumeBB = CGF.getEHResumeBlock(/*cleanup=*/true);
270       auto *CleanupContBB = CGF.createBasicBlock("cleanup.cont");
271       CGF.Builder.CreateCondBr(CoroEnd, ResumeBB, CleanupContBB);
272       CGF.EmitBlock(CleanupContBB);
273     }
274   }
275 };
276 }
277 
278 namespace {
279 // Make sure to call coro.delete on scope exit.
280 struct CallCoroDelete final : public EHScopeStack::Cleanup {
281   Stmt *Deallocate;
282 
283   // Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;"
284 
285   // Note: That deallocation will be emitted twice: once for a normal exit and
286   // once for exceptional exit. This usage is safe because Deallocate does not
287   // contain any declarations. The SubStmtBuilder::makeNewAndDeleteExpr()
288   // builds a single call to a deallocation function which is safe to emit
289   // multiple times.
290   void Emit(CodeGenFunction &CGF, Flags) override {
291     // Remember the current point, as we are going to emit deallocation code
292     // first to get to coro.free instruction that is an argument to a delete
293     // call.
294     BasicBlock *SaveInsertBlock = CGF.Builder.GetInsertBlock();
295 
296     auto *FreeBB = CGF.createBasicBlock("coro.free");
297     CGF.EmitBlock(FreeBB);
298     CGF.EmitStmt(Deallocate);
299 
300     auto *AfterFreeBB = CGF.createBasicBlock("after.coro.free");
301     CGF.EmitBlock(AfterFreeBB);
302 
303     // We should have captured coro.free from the emission of deallocate.
304     auto *CoroFree = CGF.CurCoro.Data->LastCoroFree;
305     if (!CoroFree) {
306       CGF.CGM.Error(Deallocate->getLocStart(),
307                     "Deallocation expressoin does not refer to coro.free");
308       return;
309     }
310 
311     // Get back to the block we were originally and move coro.free there.
312     auto *InsertPt = SaveInsertBlock->getTerminator();
313     CoroFree->moveBefore(InsertPt);
314     CGF.Builder.SetInsertPoint(InsertPt);
315 
316     // Add if (auto *mem = coro.free) Deallocate;
317     auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
318     auto *Cond = CGF.Builder.CreateICmpNE(CoroFree, NullPtr);
319     CGF.Builder.CreateCondBr(Cond, FreeBB, AfterFreeBB);
320 
321     // No longer need old terminator.
322     InsertPt->eraseFromParent();
323     CGF.Builder.SetInsertPoint(AfterFreeBB);
324   }
325   explicit CallCoroDelete(Stmt *DeallocStmt) : Deallocate(DeallocStmt) {}
326 };
327 }
328 
329 static void emitBodyAndFallthrough(CodeGenFunction &CGF,
330                                    const CoroutineBodyStmt &S, Stmt *Body) {
331   CGF.EmitStmt(Body);
332   const bool CanFallthrough = CGF.Builder.GetInsertBlock();
333   if (CanFallthrough)
334     if (Stmt *OnFallthrough = S.getFallthroughHandler())
335       CGF.EmitStmt(OnFallthrough);
336 }
337 
338 void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt &S) {
339   auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
340   auto &TI = CGM.getContext().getTargetInfo();
341   unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();
342 
343   auto *EntryBB = Builder.GetInsertBlock();
344   auto *AllocBB = createBasicBlock("coro.alloc");
345   auto *InitBB = createBasicBlock("coro.init");
346   auto *FinalBB = createBasicBlock("coro.final");
347   auto *RetBB = createBasicBlock("coro.ret");
348 
349   auto *CoroId = Builder.CreateCall(
350       CGM.getIntrinsic(llvm::Intrinsic::coro_id),
351       {Builder.getInt32(NewAlign), NullPtr, NullPtr, NullPtr});
352   createCoroData(*this, CurCoro, CoroId);
353   CurCoro.Data->SuspendBB = RetBB;
354 
355   // Backend is allowed to elide memory allocations, to help it, emit
356   // auto mem = coro.alloc() ? 0 : ... allocation code ...;
357   auto *CoroAlloc = Builder.CreateCall(
358       CGM.getIntrinsic(llvm::Intrinsic::coro_alloc), {CoroId});
359 
360   Builder.CreateCondBr(CoroAlloc, AllocBB, InitBB);
361 
362   EmitBlock(AllocBB);
363   auto *AllocateCall = EmitScalarExpr(S.getAllocate());
364   auto *AllocOrInvokeContBB = Builder.GetInsertBlock();
365 
366   // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
367   if (auto *RetOnAllocFailure = S.getReturnStmtOnAllocFailure()) {
368     auto *RetOnFailureBB = createBasicBlock("coro.ret.on.failure");
369 
370     // See if allocation was successful.
371     auto *NullPtr = llvm::ConstantPointerNull::get(Int8PtrTy);
372     auto *Cond = Builder.CreateICmpNE(AllocateCall, NullPtr);
373     Builder.CreateCondBr(Cond, InitBB, RetOnFailureBB);
374 
375     // If not, return OnAllocFailure object.
376     EmitBlock(RetOnFailureBB);
377     EmitStmt(RetOnAllocFailure);
378   }
379   else {
380     Builder.CreateBr(InitBB);
381   }
382 
383   EmitBlock(InitBB);
384 
385   // Pass the result of the allocation to coro.begin.
386   auto *Phi = Builder.CreatePHI(VoidPtrTy, 2);
387   Phi->addIncoming(NullPtr, EntryBB);
388   Phi->addIncoming(AllocateCall, AllocOrInvokeContBB);
389   auto *CoroBegin = Builder.CreateCall(
390       CGM.getIntrinsic(llvm::Intrinsic::coro_begin), {CoroId, Phi});
391   CurCoro.Data->CoroBegin = CoroBegin;
392 
393   CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(RetBB);
394   {
395     CodeGenFunction::RunCleanupsScope ResumeScope(*this);
396     EHStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, S.getDeallocate());
397 
398     EmitStmt(S.getPromiseDeclStmt());
399     EmitStmt(S.getResultDecl()); // FIXME: Gro lifetime is wrong.
400 
401     EHStack.pushCleanup<CallCoroEnd>(EHCleanup);
402 
403     CurCoro.Data->FinalJD = getJumpDestInCurrentScope(FinalBB);
404 
405     // FIXME: Emit param moves.
406 
407     CurCoro.Data->CurrentAwaitKind = AwaitKind::Init;
408     EmitStmt(S.getInitSuspendStmt());
409 
410     CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal;
411 
412     if (auto *OnException = S.getExceptionHandler()) {
413       auto Loc = S.getLocStart();
414       CXXCatchStmt Catch(Loc, /*exDecl=*/nullptr, OnException);
415       auto *TryStmt = CXXTryStmt::Create(getContext(), Loc, S.getBody(), &Catch);
416 
417       EnterCXXTryStmt(*TryStmt);
418       emitBodyAndFallthrough(*this, S, TryStmt->getTryBlock());
419       ExitCXXTryStmt(*TryStmt);
420     }
421     else {
422       emitBodyAndFallthrough(*this, S, S.getBody());
423     }
424 
425     // See if we need to generate final suspend.
426     const bool CanFallthrough = Builder.GetInsertBlock();
427     const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0;
428     if (CanFallthrough || HasCoreturns) {
429       EmitBlock(FinalBB);
430       CurCoro.Data->CurrentAwaitKind = AwaitKind::Final;
431       EmitStmt(S.getFinalSuspendStmt());
432     }
433   }
434 
435   EmitBlock(RetBB);
436   // Emit coro.end before getReturnStmt (and parameter destructors), since
437   // resume and destroy parts of the coroutine should not include them.
438   llvm::Function *CoroEnd = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
439   Builder.CreateCall(CoroEnd, {NullPtr, Builder.getFalse()});
440 
441   if (Stmt *Ret = S.getReturnStmt())
442     EmitStmt(Ret);
443 }
444 
445 // Emit coroutine intrinsic and patch up arguments of the token type.
446 RValue CodeGenFunction::EmitCoroutineIntrinsic(const CallExpr *E,
447                                                unsigned int IID) {
448   SmallVector<llvm::Value *, 8> Args;
449   switch (IID) {
450   default:
451     break;
452   // The coro.frame builtin is replaced with an SSA value of the coro.begin
453   // intrinsic.
454   case llvm::Intrinsic::coro_frame: {
455     if (CurCoro.Data && CurCoro.Data->CoroBegin) {
456       return RValue::get(CurCoro.Data->CoroBegin);
457     }
458     CGM.Error(E->getLocStart(), "this builtin expect that __builtin_coro_begin "
459       "has been used earlier in this function");
460     auto NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
461     return RValue::get(NullPtr);
462   }
463   // The following three intrinsics take a token parameter referring to a token
464   // returned by earlier call to @llvm.coro.id. Since we cannot represent it in
465   // builtins, we patch it up here.
466   case llvm::Intrinsic::coro_alloc:
467   case llvm::Intrinsic::coro_begin:
468   case llvm::Intrinsic::coro_free: {
469     if (CurCoro.Data && CurCoro.Data->CoroId) {
470       Args.push_back(CurCoro.Data->CoroId);
471       break;
472     }
473     CGM.Error(E->getLocStart(), "this builtin expect that __builtin_coro_id has"
474                                 " been used earlier in this function");
475     // Fallthrough to the next case to add TokenNone as the first argument.
476   }
477   // @llvm.coro.suspend takes a token parameter. Add token 'none' as the first
478   // argument.
479   case llvm::Intrinsic::coro_suspend:
480     Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
481     break;
482   }
483   for (auto &Arg : E->arguments())
484     Args.push_back(EmitScalarExpr(Arg));
485 
486   llvm::Value *F = CGM.getIntrinsic(IID);
487   llvm::CallInst *Call = Builder.CreateCall(F, Args);
488 
489   // Note: The following code is to enable to emit coro.id and coro.begin by
490   // hand to experiment with coroutines in C.
491   // If we see @llvm.coro.id remember it in the CoroData. We will update
492   // coro.alloc, coro.begin and coro.free intrinsics to refer to it.
493   if (IID == llvm::Intrinsic::coro_id) {
494     createCoroData(*this, CurCoro, Call, E);
495   }
496   else if (IID == llvm::Intrinsic::coro_begin) {
497     if (CurCoro.Data)
498       CurCoro.Data->CoroBegin = Call;
499   }
500   else if (IID == llvm::Intrinsic::coro_free) {
501     // Remember the last coro_free as we need it to build the conditional
502     // deletion of the coroutine frame.
503     if (CurCoro.Data)
504       CurCoro.Data->LastCoroFree = Call;
505   }  return RValue::get(Call);
506 }
507