clang  6.0.0svn
CGCoroutine.cpp
Go to the documentation of this file.
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 "CGCleanup.h"
15 #include "CodeGenFunction.h"
16 #include "llvm/ADT/ScopeExit.h"
17 #include "clang/AST/StmtCXX.h"
18 #include "clang/AST/StmtVisitor.h"
19 
20 using namespace clang;
21 using namespace CodeGen;
22 
23 using llvm::Value;
24 using llvm::BasicBlock;
25 
26 namespace {
27 enum class AwaitKind { Init, Normal, Yield, Final };
28 static constexpr llvm::StringLiteral AwaitKindStr[] = {"init", "await", "yield",
29  "final"};
30 }
31 
33  // What is the current await expression kind and how many
34  // await/yield expressions were encountered so far.
35  // These are used to generate pretty labels for await expressions in LLVM IR.
36  AwaitKind CurrentAwaitKind = AwaitKind::Init;
37  unsigned AwaitNum = 0;
38  unsigned YieldNum = 0;
39 
40  // How many co_return statements are in the coroutine. Used to decide whether
41  // we need to add co_return; equivalent at the end of the user authored body.
42  unsigned CoreturnCount = 0;
43 
44  // A branch to this block is emitted when coroutine needs to suspend.
45  llvm::BasicBlock *SuspendBB = nullptr;
46 
47  // Stores the jump destination just before the coroutine memory is freed.
48  // This is the destination that every suspend point jumps to for the cleanup
49  // branch.
51 
52  // Stores the jump destination just before the final suspend. The co_return
53  // statements jumps to this point after calling return_xxx promise member.
55 
56  // Stores the llvm.coro.id emitted in the function so that we can supply it
57  // as the first argument to coro.begin, coro.alloc and coro.free intrinsics.
58  // Note: llvm.coro.id returns a token that cannot be directly expressed in a
59  // builtin.
60  llvm::CallInst *CoroId = nullptr;
61 
62  // Stores the llvm.coro.begin emitted in the function so that we can replace
63  // all coro.frame intrinsics with direct SSA value of coro.begin that returns
64  // the address of the coroutine frame of the current coroutine.
65  llvm::CallInst *CoroBegin = nullptr;
66 
67  // Stores the last emitted coro.free for the deallocate expressions, we use it
68  // to wrap dealloc code with if(auto mem = coro.free) dealloc(mem).
69  llvm::CallInst *LastCoroFree = nullptr;
70 
71  // If coro.id came from the builtin, remember the expression to give better
72  // diagnostic. If CoroIdExpr is nullptr, the coro.id was created by
73  // EmitCoroutineBody.
74  CallExpr const *CoroIdExpr = nullptr;
75 };
76 
77 // Defining these here allows to keep CGCoroData private to this file.
80 
83  llvm::CallInst *CoroId,
84  CallExpr const *CoroIdExpr = nullptr) {
85  if (CurCoro.Data) {
86  if (CurCoro.Data->CoroIdExpr)
87  CGF.CGM.Error(CoroIdExpr->getLocStart(),
88  "only one __builtin_coro_id can be used in a function");
89  else if (CoroIdExpr)
90  CGF.CGM.Error(CoroIdExpr->getLocStart(),
91  "__builtin_coro_id shall not be used in a C++ coroutine");
92  else
93  llvm_unreachable("EmitCoroutineBodyStatement called twice?");
94 
95  return;
96  }
97 
98  CurCoro.Data = std::unique_ptr<CGCoroData>(new CGCoroData);
99  CurCoro.Data->CoroId = CoroId;
100  CurCoro.Data->CoroIdExpr = CoroIdExpr;
101 }
102 
103 // Synthesize a pretty name for a suspend point.
105  unsigned No = 0;
106  switch (Kind) {
107  case AwaitKind::Init:
108  case AwaitKind::Final:
109  break;
110  case AwaitKind::Normal:
111  No = ++Coro.AwaitNum;
112  break;
113  case AwaitKind::Yield:
114  No = ++Coro.YieldNum;
115  break;
116  }
117  SmallString<32> Prefix(AwaitKindStr[static_cast<unsigned>(Kind)]);
118  if (No > 1) {
119  Twine(No).toVector(Prefix);
120  }
121  return Prefix;
122 }
123 
124 // Emit suspend expression which roughly looks like:
125 //
126 // auto && x = CommonExpr();
127 // if (!x.await_ready()) {
128 // llvm_coro_save();
129 // x.await_suspend(...); (*)
130 // llvm_coro_suspend(); (**)
131 // }
132 // x.await_resume();
133 //
134 // where the result of the entire expression is the result of x.await_resume()
135 //
136 // (*) If x.await_suspend return type is bool, it allows to veto a suspend:
137 // if (x.await_suspend(...))
138 // llvm_coro_suspend();
139 //
140 // (**) llvm_coro_suspend() encodes three possible continuations as
141 // a switch instruction:
142 //
143 // %where-to = call i8 @llvm.coro.suspend(...)
144 // switch i8 %where-to, label %coro.ret [ ; jump to epilogue to suspend
145 // i8 0, label %yield.ready ; go here when resumed
146 // i8 1, label %yield.cleanup ; go here when destroyed
147 // ]
148 //
149 // See llvm's docs/Coroutines.rst for more details.
150 //
151 namespace {
152  struct LValueOrRValue {
153  LValue LV;
154  RValue RV;
155  };
156 }
157 static LValueOrRValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro,
158  CoroutineSuspendExpr const &S,
159  AwaitKind Kind, AggValueSlot aggSlot,
160  bool ignoreResult, bool forLValue) {
161  auto *E = S.getCommonExpr();
162 
163  auto Binder =
165  auto UnbindOnExit = llvm::make_scope_exit([&] { Binder.unbind(CGF); });
166 
167  auto Prefix = buildSuspendPrefixStr(Coro, Kind);
168  BasicBlock *ReadyBlock = CGF.createBasicBlock(Prefix + Twine(".ready"));
169  BasicBlock *SuspendBlock = CGF.createBasicBlock(Prefix + Twine(".suspend"));
170  BasicBlock *CleanupBlock = CGF.createBasicBlock(Prefix + Twine(".cleanup"));
171 
172  // If expression is ready, no need to suspend.
173  CGF.EmitBranchOnBoolExpr(S.getReadyExpr(), ReadyBlock, SuspendBlock, 0);
174 
175  // Otherwise, emit suspend logic.
176  CGF.EmitBlock(SuspendBlock);
177 
178  auto &Builder = CGF.Builder;
179  llvm::Function *CoroSave = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_save);
180  auto *NullPtr = llvm::ConstantPointerNull::get(CGF.CGM.Int8PtrTy);
181  auto *SaveCall = Builder.CreateCall(CoroSave, {NullPtr});
182 
183  auto *SuspendRet = CGF.EmitScalarExpr(S.getSuspendExpr());
184  if (SuspendRet != nullptr && SuspendRet->getType()->isIntegerTy(1)) {
185  // Veto suspension if requested by bool returning await_suspend.
186  BasicBlock *RealSuspendBlock =
187  CGF.createBasicBlock(Prefix + Twine(".suspend.bool"));
188  CGF.Builder.CreateCondBr(SuspendRet, RealSuspendBlock, ReadyBlock);
189  SuspendBlock = RealSuspendBlock;
190  CGF.EmitBlock(RealSuspendBlock);
191  }
192 
193  // Emit the suspend point.
194  const bool IsFinalSuspend = (Kind == AwaitKind::Final);
195  llvm::Function *CoroSuspend =
196  CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_suspend);
197  auto *SuspendResult = Builder.CreateCall(
198  CoroSuspend, {SaveCall, Builder.getInt1(IsFinalSuspend)});
199 
200  // Create a switch capturing three possible continuations.
201  auto *Switch = Builder.CreateSwitch(SuspendResult, Coro.SuspendBB, 2);
202  Switch->addCase(Builder.getInt8(0), ReadyBlock);
203  Switch->addCase(Builder.getInt8(1), CleanupBlock);
204 
205  // Emit cleanup for this suspend point.
206  CGF.EmitBlock(CleanupBlock);
208 
209  // Emit await_resume expression.
210  CGF.EmitBlock(ReadyBlock);
211  LValueOrRValue Res;
212  if (forLValue)
213  Res.LV = CGF.EmitLValue(S.getResumeExpr());
214  else
215  Res.RV = CGF.EmitAnyExpr(S.getResumeExpr(), aggSlot, ignoreResult);
216  return Res;
217 }
218 
220  AggValueSlot aggSlot,
221  bool ignoreResult) {
222  return emitSuspendExpression(*this, *CurCoro.Data, E,
223  CurCoro.Data->CurrentAwaitKind, aggSlot,
224  ignoreResult, /*forLValue*/false).RV;
225 }
227  AggValueSlot aggSlot,
228  bool ignoreResult) {
229  return emitSuspendExpression(*this, *CurCoro.Data, E, AwaitKind::Yield,
230  aggSlot, ignoreResult, /*forLValue*/false).RV;
231 }
232 
234  ++CurCoro.Data->CoreturnCount;
235  const Expr *RV = S.getOperand();
236  if (RV && RV->getType()->isVoidType()) {
237  // Make sure to evaluate the expression of a co_return with a void
238  // expression for side effects.
239  RunCleanupsScope cleanupScope(*this);
240  EmitIgnoredExpr(RV);
241  }
242  EmitStmt(S.getPromiseCall());
243  EmitBranchThroughCleanup(CurCoro.Data->FinalJD);
244 }
245 
246 
247 #ifndef NDEBUG
249  const CoroutineSuspendExpr *E) {
250  const auto *RE = E->getResumeExpr();
251  // Is it possible for RE to be a CXXBindTemporaryExpr wrapping
252  // a MemberCallExpr?
253  assert(isa<CallExpr>(RE) && "unexpected suspend expression type");
254  return cast<CallExpr>(RE)->getCallReturnType(Ctx);
255 }
256 #endif
257 
258 LValue
260  assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
261  "Can't have a scalar return unless the return type is a "
262  "reference type!");
263  return emitSuspendExpression(*this, *CurCoro.Data, *E,
264  CurCoro.Data->CurrentAwaitKind, AggValueSlot::ignored(),
265  /*ignoreResult*/false, /*forLValue*/true).LV;
266 }
267 
268 LValue
270  assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
271  "Can't have a scalar return unless the return type is a "
272  "reference type!");
273  return emitSuspendExpression(*this, *CurCoro.Data, *E,
274  AwaitKind::Yield, AggValueSlot::ignored(),
275  /*ignoreResult*/false, /*forLValue*/true).LV;
276 }
277 
278 // Hunts for the parameter reference in the parameter copy/move declaration.
279 namespace {
280 struct GetParamRef : public StmtVisitor<GetParamRef> {
281 public:
282  DeclRefExpr *Expr = nullptr;
283  GetParamRef() {}
284  void VisitDeclRefExpr(DeclRefExpr *E) {
285  assert(Expr == nullptr && "multilple declref in param move");
286  Expr = E;
287  }
288  void VisitStmt(Stmt *S) {
289  for (auto *C : S->children()) {
290  if (C)
291  Visit(C);
292  }
293  }
294 };
295 }
296 
297 // This class replaces references to parameters to their copies by changing
298 // the addresses in CGF.LocalDeclMap and restoring back the original values in
299 // its destructor.
300 
301 namespace {
302  struct ParamReferenceReplacerRAII {
303  CodeGenFunction::DeclMapTy SavedLocals;
304  CodeGenFunction::DeclMapTy& LocalDeclMap;
305 
306  ParamReferenceReplacerRAII(CodeGenFunction::DeclMapTy &LocalDeclMap)
307  : LocalDeclMap(LocalDeclMap) {}
308 
309  void addCopy(DeclStmt const *PM) {
310  // Figure out what param it refers to.
311 
312  assert(PM->isSingleDecl());
313  VarDecl const*VD = static_cast<VarDecl const*>(PM->getSingleDecl());
314  Expr const *InitExpr = VD->getInit();
315  GetParamRef Visitor;
316  Visitor.Visit(const_cast<Expr*>(InitExpr));
317  assert(Visitor.Expr);
318  auto *DREOrig = cast<DeclRefExpr>(Visitor.Expr);
319  auto *PD = DREOrig->getDecl();
320 
321  auto it = LocalDeclMap.find(PD);
322  assert(it != LocalDeclMap.end() && "parameter is not found");
323  SavedLocals.insert({ PD, it->second });
324 
325  auto copyIt = LocalDeclMap.find(VD);
326  assert(copyIt != LocalDeclMap.end() && "parameter copy is not found");
327  it->second = copyIt->getSecond();
328  }
329 
330  ~ParamReferenceReplacerRAII() {
331  for (auto&& SavedLocal : SavedLocals) {
332  LocalDeclMap.insert({SavedLocal.first, SavedLocal.second});
333  }
334  }
335  };
336 }
337 
338 // For WinEH exception representation backend needs to know what funclet coro.end
339 // belongs to. That information is passed in a funclet bundle.
343 
344  if (llvm::Instruction *EHPad = CGF.CurrentFuncletPad)
345  BundleList.emplace_back("funclet", EHPad);
346 
347  return BundleList;
348 }
349 
350 namespace {
351 // We will insert coro.end to cut any of the destructors for objects that
352 // do not need to be destroyed once the coroutine is resumed.
353 // See llvm/docs/Coroutines.rst for more details about coro.end.
354 struct CallCoroEnd final : public EHScopeStack::Cleanup {
355  void Emit(CodeGenFunction &CGF, Flags flags) override {
356  auto &CGM = CGF.CGM;
357  auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
358  llvm::Function *CoroEndFn = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
359  // See if we have a funclet bundle to associate coro.end with. (WinEH)
360  auto Bundles = getBundlesForCoroEnd(CGF);
361  auto *CoroEnd = CGF.Builder.CreateCall(
362  CoroEndFn, {NullPtr, CGF.Builder.getTrue()}, Bundles);
363  if (Bundles.empty()) {
364  // Otherwise, (landingpad model), create a conditional branch that leads
365  // either to a cleanup block or a block with EH resume instruction.
366  auto *ResumeBB = CGF.getEHResumeBlock(/*cleanup=*/true);
367  auto *CleanupContBB = CGF.createBasicBlock("cleanup.cont");
368  CGF.Builder.CreateCondBr(CoroEnd, ResumeBB, CleanupContBB);
369  CGF.EmitBlock(CleanupContBB);
370  }
371  }
372 };
373 }
374 
375 namespace {
376 // Make sure to call coro.delete on scope exit.
377 struct CallCoroDelete final : public EHScopeStack::Cleanup {
378  Stmt *Deallocate;
379 
380  // Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;"
381 
382  // Note: That deallocation will be emitted twice: once for a normal exit and
383  // once for exceptional exit. This usage is safe because Deallocate does not
384  // contain any declarations. The SubStmtBuilder::makeNewAndDeleteExpr()
385  // builds a single call to a deallocation function which is safe to emit
386  // multiple times.
387  void Emit(CodeGenFunction &CGF, Flags) override {
388  // Remember the current point, as we are going to emit deallocation code
389  // first to get to coro.free instruction that is an argument to a delete
390  // call.
391  BasicBlock *SaveInsertBlock = CGF.Builder.GetInsertBlock();
392 
393  auto *FreeBB = CGF.createBasicBlock("coro.free");
394  CGF.EmitBlock(FreeBB);
395  CGF.EmitStmt(Deallocate);
396 
397  auto *AfterFreeBB = CGF.createBasicBlock("after.coro.free");
398  CGF.EmitBlock(AfterFreeBB);
399 
400  // We should have captured coro.free from the emission of deallocate.
401  auto *CoroFree = CGF.CurCoro.Data->LastCoroFree;
402  if (!CoroFree) {
403  CGF.CGM.Error(Deallocate->getLocStart(),
404  "Deallocation expressoin does not refer to coro.free");
405  return;
406  }
407 
408  // Get back to the block we were originally and move coro.free there.
409  auto *InsertPt = SaveInsertBlock->getTerminator();
410  CoroFree->moveBefore(InsertPt);
411  CGF.Builder.SetInsertPoint(InsertPt);
412 
413  // Add if (auto *mem = coro.free) Deallocate;
414  auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
415  auto *Cond = CGF.Builder.CreateICmpNE(CoroFree, NullPtr);
416  CGF.Builder.CreateCondBr(Cond, FreeBB, AfterFreeBB);
417 
418  // No longer need old terminator.
419  InsertPt->eraseFromParent();
420  CGF.Builder.SetInsertPoint(AfterFreeBB);
421  }
422  explicit CallCoroDelete(Stmt *DeallocStmt) : Deallocate(DeallocStmt) {}
423 };
424 }
425 
426 namespace {
427 struct GetReturnObjectManager {
428  CodeGenFunction &CGF;
429  CGBuilderTy &Builder;
430  const CoroutineBodyStmt &S;
431 
432  Address GroActiveFlag;
434 
435  GetReturnObjectManager(CodeGenFunction &CGF, const CoroutineBodyStmt &S)
436  : CGF(CGF), Builder(CGF.Builder), S(S), GroActiveFlag(Address::invalid()),
438 
439  // The gro variable has to outlive coroutine frame and coroutine promise, but,
440  // it can only be initialized after coroutine promise was created, thus, we
441  // split its emission in two parts. EmitGroAlloca emits an alloca and sets up
442  // cleanups. Later when coroutine promise is available we initialize the gro
443  // and sets the flag that the cleanup is now active.
444 
445  void EmitGroAlloca() {
446  auto *GroDeclStmt = dyn_cast<DeclStmt>(S.getResultDecl());
447  if (!GroDeclStmt) {
448  // If get_return_object returns void, no need to do an alloca.
449  return;
450  }
451 
452  auto *GroVarDecl = cast<VarDecl>(GroDeclStmt->getSingleDecl());
453 
454  // Set GRO flag that it is not initialized yet
455  GroActiveFlag =
456  CGF.CreateTempAlloca(Builder.getInt1Ty(), CharUnits::One(), "gro.active");
457  Builder.CreateStore(Builder.getFalse(), GroActiveFlag);
458 
459  GroEmission = CGF.EmitAutoVarAlloca(*GroVarDecl);
460 
461  // Remember the top of EHStack before emitting the cleanup.
462  auto old_top = CGF.EHStack.stable_begin();
463  CGF.EmitAutoVarCleanups(GroEmission);
464  auto top = CGF.EHStack.stable_begin();
465 
466  // Make the cleanup conditional on gro.active
467  for (auto b = CGF.EHStack.find(top), e = CGF.EHStack.find(old_top);
468  b != e; b++) {
469  if (auto *Cleanup = dyn_cast<EHCleanupScope>(&*b)) {
470  assert(!Cleanup->hasActiveFlag() && "cleanup already has active flag?");
471  Cleanup->setActiveFlag(GroActiveFlag);
472  Cleanup->setTestFlagInEHCleanup();
473  Cleanup->setTestFlagInNormalCleanup();
474  }
475  }
476  }
477 
478  void EmitGroInit() {
479  if (!GroActiveFlag.isValid()) {
480  // No Gro variable was allocated. Simply emit the call to
481  // get_return_object.
482  CGF.EmitStmt(S.getResultDecl());
483  return;
484  }
485 
486  CGF.EmitAutoVarInit(GroEmission);
487  Builder.CreateStore(Builder.getTrue(), GroActiveFlag);
488  }
489 };
490 }
491 
493  const CoroutineBodyStmt &S, Stmt *Body) {
494  CGF.EmitStmt(Body);
495  const bool CanFallthrough = CGF.Builder.GetInsertBlock();
496  if (CanFallthrough)
497  if (Stmt *OnFallthrough = S.getFallthroughHandler())
498  CGF.EmitStmt(OnFallthrough);
499 }
500 
502  auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
503  auto &TI = CGM.getContext().getTargetInfo();
504  unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();
505 
506  auto *EntryBB = Builder.GetInsertBlock();
507  auto *AllocBB = createBasicBlock("coro.alloc");
508  auto *InitBB = createBasicBlock("coro.init");
509  auto *FinalBB = createBasicBlock("coro.final");
510  auto *RetBB = createBasicBlock("coro.ret");
511 
512  auto *CoroId = Builder.CreateCall(
513  CGM.getIntrinsic(llvm::Intrinsic::coro_id),
514  {Builder.getInt32(NewAlign), NullPtr, NullPtr, NullPtr});
515  createCoroData(*this, CurCoro, CoroId);
516  CurCoro.Data->SuspendBB = RetBB;
517 
518  // Backend is allowed to elide memory allocations, to help it, emit
519  // auto mem = coro.alloc() ? 0 : ... allocation code ...;
520  auto *CoroAlloc = Builder.CreateCall(
521  CGM.getIntrinsic(llvm::Intrinsic::coro_alloc), {CoroId});
522 
523  Builder.CreateCondBr(CoroAlloc, AllocBB, InitBB);
524 
525  EmitBlock(AllocBB);
526  auto *AllocateCall = EmitScalarExpr(S.getAllocate());
527  auto *AllocOrInvokeContBB = Builder.GetInsertBlock();
528 
529  // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
530  if (auto *RetOnAllocFailure = S.getReturnStmtOnAllocFailure()) {
531  auto *RetOnFailureBB = createBasicBlock("coro.ret.on.failure");
532 
533  // See if allocation was successful.
534  auto *NullPtr = llvm::ConstantPointerNull::get(Int8PtrTy);
535  auto *Cond = Builder.CreateICmpNE(AllocateCall, NullPtr);
536  Builder.CreateCondBr(Cond, InitBB, RetOnFailureBB);
537 
538  // If not, return OnAllocFailure object.
539  EmitBlock(RetOnFailureBB);
540  EmitStmt(RetOnAllocFailure);
541  }
542  else {
543  Builder.CreateBr(InitBB);
544  }
545 
546  EmitBlock(InitBB);
547 
548  // Pass the result of the allocation to coro.begin.
549  auto *Phi = Builder.CreatePHI(VoidPtrTy, 2);
550  Phi->addIncoming(NullPtr, EntryBB);
551  Phi->addIncoming(AllocateCall, AllocOrInvokeContBB);
552  auto *CoroBegin = Builder.CreateCall(
553  CGM.getIntrinsic(llvm::Intrinsic::coro_begin), {CoroId, Phi});
554  CurCoro.Data->CoroBegin = CoroBegin;
555 
556  GetReturnObjectManager GroManager(*this, S);
557  GroManager.EmitGroAlloca();
558 
559  CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(RetBB);
560  {
561  ParamReferenceReplacerRAII ParamReplacer(LocalDeclMap);
562  CodeGenFunction::RunCleanupsScope ResumeScope(*this);
563  EHStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, S.getDeallocate());
564 
565  // Create parameter copies. We do it before creating a promise, since an
566  // evolution of coroutine TS may allow promise constructor to observe
567  // parameter copies.
568  for (auto *PM : S.getParamMoves()) {
569  EmitStmt(PM);
570  ParamReplacer.addCopy(cast<DeclStmt>(PM));
571  // TODO: if(CoroParam(...)) need to surround ctor and dtor
572  // for the copy, so that llvm can elide it if the copy is
573  // not needed.
574  }
575 
576  EmitStmt(S.getPromiseDeclStmt());
577 
578  Address PromiseAddr = GetAddrOfLocalVar(S.getPromiseDecl());
579  auto *PromiseAddrVoidPtr =
580  new llvm::BitCastInst(PromiseAddr.getPointer(), VoidPtrTy, "", CoroId);
581  // Update CoroId to refer to the promise. We could not do it earlier because
582  // promise local variable was not emitted yet.
583  CoroId->setArgOperand(1, PromiseAddrVoidPtr);
584 
585  // Now we have the promise, initialize the GRO
586  GroManager.EmitGroInit();
587 
588  EHStack.pushCleanup<CallCoroEnd>(EHCleanup);
589 
590  CurCoro.Data->CurrentAwaitKind = AwaitKind::Init;
591  EmitStmt(S.getInitSuspendStmt());
592  CurCoro.Data->FinalJD = getJumpDestInCurrentScope(FinalBB);
593 
594  CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal;
595 
596  if (auto *OnException = S.getExceptionHandler()) {
597  auto Loc = S.getLocStart();
598  CXXCatchStmt Catch(Loc, /*exDecl=*/nullptr, OnException);
599  auto *TryStmt = CXXTryStmt::Create(getContext(), Loc, S.getBody(), &Catch);
600 
601  EnterCXXTryStmt(*TryStmt);
602  emitBodyAndFallthrough(*this, S, TryStmt->getTryBlock());
603  ExitCXXTryStmt(*TryStmt);
604  }
605  else {
606  emitBodyAndFallthrough(*this, S, S.getBody());
607  }
608 
609  // See if we need to generate final suspend.
610  const bool CanFallthrough = Builder.GetInsertBlock();
611  const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0;
612  if (CanFallthrough || HasCoreturns) {
613  EmitBlock(FinalBB);
614  CurCoro.Data->CurrentAwaitKind = AwaitKind::Final;
615  EmitStmt(S.getFinalSuspendStmt());
616  } else {
617  // We don't need FinalBB. Emit it to make sure the block is deleted.
618  EmitBlock(FinalBB, /*IsFinished=*/true);
619  }
620  }
621 
622  EmitBlock(RetBB);
623  // Emit coro.end before getReturnStmt (and parameter destructors), since
624  // resume and destroy parts of the coroutine should not include them.
625  llvm::Function *CoroEnd = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
626  Builder.CreateCall(CoroEnd, {NullPtr, Builder.getFalse()});
627 
628  if (Stmt *Ret = S.getReturnStmt())
629  EmitStmt(Ret);
630 }
631 
632 // Emit coroutine intrinsic and patch up arguments of the token type.
634  unsigned int IID) {
636  switch (IID) {
637  default:
638  break;
639  // The coro.frame builtin is replaced with an SSA value of the coro.begin
640  // intrinsic.
641  case llvm::Intrinsic::coro_frame: {
642  if (CurCoro.Data && CurCoro.Data->CoroBegin) {
643  return RValue::get(CurCoro.Data->CoroBegin);
644  }
645  CGM.Error(E->getLocStart(), "this builtin expect that __builtin_coro_begin "
646  "has been used earlier in this function");
647  auto NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
648  return RValue::get(NullPtr);
649  }
650  // The following three intrinsics take a token parameter referring to a token
651  // returned by earlier call to @llvm.coro.id. Since we cannot represent it in
652  // builtins, we patch it up here.
653  case llvm::Intrinsic::coro_alloc:
654  case llvm::Intrinsic::coro_begin:
655  case llvm::Intrinsic::coro_free: {
656  if (CurCoro.Data && CurCoro.Data->CoroId) {
657  Args.push_back(CurCoro.Data->CoroId);
658  break;
659  }
660  CGM.Error(E->getLocStart(), "this builtin expect that __builtin_coro_id has"
661  " been used earlier in this function");
662  // Fallthrough to the next case to add TokenNone as the first argument.
663  LLVM_FALLTHROUGH;
664  }
665  // @llvm.coro.suspend takes a token parameter. Add token 'none' as the first
666  // argument.
667  case llvm::Intrinsic::coro_suspend:
668  Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
669  break;
670  }
671  for (auto &Arg : E->arguments())
672  Args.push_back(EmitScalarExpr(Arg));
673 
674  llvm::Value *F = CGM.getIntrinsic(IID);
675  llvm::CallInst *Call = Builder.CreateCall(F, Args);
676 
677  // Note: The following code is to enable to emit coro.id and coro.begin by
678  // hand to experiment with coroutines in C.
679  // If we see @llvm.coro.id remember it in the CoroData. We will update
680  // coro.alloc, coro.begin and coro.free intrinsics to refer to it.
681  if (IID == llvm::Intrinsic::coro_id) {
682  createCoroData(*this, CurCoro, Call, E);
683  }
684  else if (IID == llvm::Intrinsic::coro_begin) {
685  if (CurCoro.Data)
686  CurCoro.Data->CoroBegin = Call;
687  }
688  else if (IID == llvm::Intrinsic::coro_free) {
689  // Remember the last coro_free as we need it to build the conditional
690  // deletion of the coroutine frame.
691  if (CurCoro.Data)
692  CurCoro.Data->LastCoroFree = Call;
693  }
694  return RValue::get(Call);
695 }
Expr * getReadyExpr() const
Definition: ExprCXX.h:4176
void EmitCoroutineBody(const CoroutineBodyStmt &S)
A (possibly-)qualified type.
Definition: Type.h:614
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount)
EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g.
RValue EmitCoyieldExpr(const CoyieldExpr &E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
Stmt - This represents one statement.
Definition: Stmt.h:60
Represents a &#39;co_return&#39; statement in the C++ Coroutines TS.
Definition: StmtCXX.h:432
RValue EmitCoawaitExpr(const CoawaitExpr &E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
Stmt * getPromiseDeclStmt() const
Definition: StmtCXX.h:364
iterator find(stable_iterator save) const
Turn a stable reference to a scope depth into a unstable pointer to the EH stack. ...
Definition: CGCleanup.h:591
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
Definition: EHScopeStack.h:379
Stmt * getExceptionHandler() const
Definition: StmtCXX.h:378
Expr * getDeallocate() const
Definition: StmtCXX.h:388
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:771
Stmt * getResultDecl() const
Definition: StmtCXX.h:394
A jump destination is an abstract label, branching to which may require a jump out through normal cle...
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:128
VarDecl * getPromiseDecl() const
Definition: StmtCXX.h:367
LValue EmitCoyieldLValue(const CoyieldExpr *E)
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
Definition: EHScopeStack.h:81
RValue EmitAnyExpr(const Expr *E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
EmitAnyExpr - Emit code to compute the specified expression which can have any type.
Definition: CGExpr.cpp:170
ArrayRef< Stmt const * > getParamMoves() const
Definition: StmtCXX.h:399
child_range children()
Definition: Stmt.cpp:208
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition: ExprCXX.h:4174
Expr * getCommonExpr() const
Definition: ExprCXX.h:4170
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
Definition: CGExpr.cpp:91
Stmt * getReturnStmt() const
Definition: StmtCXX.h:395
static QualType getCoroutineSuspendExprReturnType(const ASTContext &Ctx, const CoroutineSuspendExpr *E)
bool isValid() const
Definition: Address.h:36
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition: CharUnits.h:58
AutoVarEmission EmitAutoVarAlloca(const VarDecl &var)
EmitAutoVarAlloca - Emit the alloca and debug information for a local variable.
Definition: CGDecl.cpp:957
RValue - This trivial value class is used to represent the result of an expression that is evaluated...
Definition: CGValue.h:39
static SmallVector< llvm::OperandBundleDef, 1 > getBundlesForCoroEnd(CodeGenFunction &CGF)
static SmallString< 32 > buildSuspendPrefixStr(CGCoroData &Coro, AwaitKind Kind)
Expr - This represents one expression.
Definition: Expr.h:106
void EmitAutoVarInit(const AutoVarEmission &emission)
Definition: CGDecl.cpp:1207
static Address invalid()
Definition: Address.h:35
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited...
QualType getType() const
Definition: Expr.h:128
SourceLocation getLocStart() const LLVM_READONLY
Definition: StmtCXX.h:403
CodeGenFunction::JumpDest FinalJD
Definition: CGCoroutine.cpp:54
Kind
static LValueOrRValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro, CoroutineSuspendExpr const &S, AwaitKind Kind, AggValueSlot aggSlot, bool ignoreResult, bool forLValue)
RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID)
DeclStmt - Adaptor class for mixing declarations with statements and expressions. ...
Definition: Stmt.h:467
An aggregate value slot.
Definition: CGValue.h:440
CodeGenFunction::JumpDest CleanupJD
Definition: CGCoroutine.cpp:50
void EmitStmt(const Stmt *S, ArrayRef< const Attr *> Attrs=None)
EmitStmt - Emit the code for the statement.
Definition: CGStmt.cpp:48
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:180
Expr * getSuspendExpr() const
Definition: ExprCXX.h:4179
arg_range arguments()
Definition: Expr.h:2303
An aligned address.
Definition: Address.h:25
llvm::BasicBlock * SuspendBB
Definition: CGCoroutine.cpp:45
llvm::BasicBlock * getEHResumeBlock(bool isCleanup)
llvm::Instruction * CurrentFuncletPad
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can&#39;t be done.
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type, returning the result.
Dataflow Directional Tag Classes.
Stmt * getReturnStmtOnAllocFailure() const
Definition: StmtCXX.h:396
Expr * getAllocate() const
Definition: StmtCXX.h:385
static AggValueSlot ignored()
ignored - Returns an aggregate value slot indicating that the aggregate value is being ignored...
Definition: CGValue.h:486
Represents a &#39;co_yield&#39; expression.
Definition: ExprCXX.h:4281
Expr * getOperand() const
Retrieve the operand of the &#39;co_return&#39; statement.
Definition: StmtCXX.h:456
const Decl * getSingleDecl() const
Definition: Stmt.h:485
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type *> Tys=None)
Stmt * getInitSuspendStmt() const
Definition: StmtCXX.h:371
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:108
AwaitKind
Definition: CGCoroutine.cpp:27
bool isSingleDecl() const
isSingleDecl - This method returns true if this DeclStmt refers to a single Decl. ...
Definition: Stmt.h:481
void EmitCoreturnStmt(const CoreturnStmt &S)
static void emitBodyAndFallthrough(CodeGenFunction &CGF, const CoroutineBodyStmt &S, Stmt *Body)
llvm::DenseMap< const Decl *, Address > DeclMapTy
void EmitAutoVarCleanups(const AutoVarEmission &emission)
Definition: CGDecl.cpp:1417
static void createCoroData(CodeGenFunction &CGF, CodeGenFunction::CGCoroInfo &CurCoro, llvm::CallInst *CoroId, CallExpr const *CoroIdExpr=nullptr)
Definition: CGCoroutine.cpp:81
Represents the body of a coroutine.
Definition: StmtCXX.h:299
Represents a &#39;co_await&#39; expression.
Definition: ExprCXX.h:4204
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.cpp:1326
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition: CGStmt.cpp:436
Represents an expression that might suspend coroutine execution; either a co_await or co_yield expres...
Definition: ExprCXX.h:4128
Expr * getResumeExpr() const
Definition: ExprCXX.h:4182
static OpaqueValueMappingData bind(CodeGenFunction &CGF, const OpaqueValueExpr *ov, const Expr *e)
Expr * getPromiseCall() const
Retrieve the promise call that results from this &#39;co_return&#39; statement.
Definition: StmtCXX.h:461
LValue EmitCoawaitLValue(const CoawaitExpr *E)
bool isVoidType() const
Definition: Type.h:5963
Stmt * getFallthroughHandler() const
Definition: StmtCXX.h:381
static CXXTryStmt * Create(const ASTContext &C, SourceLocation tryLoc, Stmt *tryBlock, ArrayRef< Stmt *> handlers)
Definition: StmtCXX.cpp:26
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:29
LValue EmitLValue(const Expr *E)
EmitLValue - Emit code to compute a designator that specifies the location of the expression...
Definition: CGExpr.cpp:1121
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2209
Stmt * getBody() const
Retrieve the body of the coroutine as written.
Definition: StmtCXX.h:360
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:956
static RValue get(llvm::Value *V)
Definition: CGValue.h:86
void EmitBranchThroughCleanup(JumpDest Dest)
EmitBranchThroughCleanup - Emit a branch from the current insert block through the normal cleanup han...
Definition: CGCleanup.cpp:1034
LValue - This represents an lvalue references.
Definition: CGValue.h:172
Information for lazily generating a cleanup.
Definition: EHScopeStack.h:147
Stmt * getFinalSuspendStmt() const
Definition: StmtCXX.h:374