Coverage Report

Created: 2020-02-25 14:32

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CGCoroutine.cpp
Line
Count
Source (jump to first uncovered line)
1
//===----- CGCoroutine.cpp - Emit LLVM Code for C++ coroutines ------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This contains code dealing with C++ code generation of coroutines.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "CGCleanup.h"
14
#include "CodeGenFunction.h"
15
#include "llvm/ADT/ScopeExit.h"
16
#include "clang/AST/StmtCXX.h"
17
#include "clang/AST/StmtVisitor.h"
18
19
using namespace clang;
20
using namespace CodeGen;
21
22
using llvm::Value;
23
using llvm::BasicBlock;
24
25
namespace {
26
enum class AwaitKind { Init, Normal, Yield, Final };
27
static constexpr llvm::StringLiteral AwaitKindStr[] = {"init", "await", "yield",
28
                                                       "final"};
29
}
30
31
struct 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
  // The promise type's 'unhandled_exception' handler, if it defines one.
47
  Stmt *ExceptionHandler = nullptr;
48
49
  // A temporary i1 alloca that stores whether 'await_resume' threw an
50
  // exception. If it did, 'true' is stored in this variable, and the coroutine
51
  // body must be skipped. If the promise type does not define an exception
52
  // handler, this is null.
53
  llvm::Value *ResumeEHVar = nullptr;
54
55
  // Stores the jump destination just before the coroutine memory is freed.
56
  // This is the destination that every suspend point jumps to for the cleanup
57
  // branch.
58
  CodeGenFunction::JumpDest CleanupJD;
59
60
  // Stores the jump destination just before the final suspend. The co_return
61
  // statements jumps to this point after calling return_xxx promise member.
62
  CodeGenFunction::JumpDest FinalJD;
63
64
  // Stores the llvm.coro.id emitted in the function so that we can supply it
65
  // as the first argument to coro.begin, coro.alloc and coro.free intrinsics.
66
  // Note: llvm.coro.id returns a token that cannot be directly expressed in a
67
  // builtin.
68
  llvm::CallInst *CoroId = nullptr;
69
70
  // Stores the llvm.coro.begin emitted in the function so that we can replace
71
  // all coro.frame intrinsics with direct SSA value of coro.begin that returns
72
  // the address of the coroutine frame of the current coroutine.
73
  llvm::CallInst *CoroBegin = nullptr;
74
75
  // Stores the last emitted coro.free for the deallocate expressions, we use it
76
  // to wrap dealloc code with if(auto mem = coro.free) dealloc(mem).
77
  llvm::CallInst *LastCoroFree = nullptr;
78
79
  // If coro.id came from the builtin, remember the expression to give better
80
  // diagnostic. If CoroIdExpr is nullptr, the coro.id was created by
81
  // EmitCoroutineBody.
82
  CallExpr const *CoroIdExpr = nullptr;
83
};
84
85
// Defining these here allows to keep CGCoroData private to this file.
86
243k
clang::CodeGen::CodeGenFunction::CGCoroInfo::CGCoroInfo() {}
87
243k
CodeGenFunction::CGCoroInfo::~CGCoroInfo() {}
88
89
static void createCoroData(CodeGenFunction &CGF,
90
                           CodeGenFunction::CGCoroInfo &CurCoro,
91
                           llvm::CallInst *CoroId,
92
47
                           CallExpr const *CoroIdExpr = nullptr) {
93
47
  if (CurCoro.Data) {
94
1
    if (CurCoro.Data->CoroIdExpr)
95
1
      CGF.CGM.Error(CoroIdExpr->getBeginLoc(),
96
1
                    "only one __builtin_coro_id can be used in a function");
97
0
    else if (CoroIdExpr)
98
0
      CGF.CGM.Error(CoroIdExpr->getBeginLoc(),
99
0
                    "__builtin_coro_id shall not be used in a C++ coroutine");
100
0
    else
101
0
      llvm_unreachable("EmitCoroutineBodyStatement called twice?");
102
1
103
1
    return;
104
46
  }
105
46
106
46
  CurCoro.Data = std::unique_ptr<CGCoroData>(new CGCoroData);
107
46
  CurCoro.Data->CoroId = CoroId;
108
46
  CurCoro.Data->CoroIdExpr = CoroIdExpr;
109
46
}
110
111
// Synthesize a pretty name for a suspend point.
112
110
static SmallString<32> buildSuspendPrefixStr(CGCoroData &Coro, AwaitKind Kind) {
113
110
  unsigned No = 0;
114
110
  switch (Kind) {
115
86
  case AwaitKind::Init:
116
86
  case AwaitKind::Final:
117
86
    break;
118
86
  case AwaitKind::Normal:
119
22
    No = ++Coro.AwaitNum;
120
22
    break;
121
86
  case AwaitKind::Yield:
122
2
    No = ++Coro.YieldNum;
123
2
    break;
124
110
  }
125
110
  SmallString<32> Prefix(AwaitKindStr[static_cast<unsigned>(Kind)]);
126
110
  if (No > 1) {
127
8
    Twine(No).toVector(Prefix);
128
8
  }
129
110
  return Prefix;
130
110
}
131
132
10
static bool memberCallExpressionCanThrow(const Expr *E) {
133
10
  if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
134
10
    if (const auto *Proto =
135
10
            CE->getMethodDecl()->getType()->getAs<FunctionProtoType>())
136
10
      if (isNoexceptExceptionSpec(Proto->getExceptionSpecType()) &&
137
10
          
Proto->canThrow() == CT_Cannot6
)
138
6
        return false;
139
4
  return true;
140
4
}
141
142
// Emit suspend expression which roughly looks like:
143
//
144
//   auto && x = CommonExpr();
145
//   if (!x.await_ready()) {
146
//      llvm_coro_save();
147
//      x.await_suspend(...);     (*)
148
//      llvm_coro_suspend(); (**)
149
//   }
150
//   x.await_resume();
151
//
152
// where the result of the entire expression is the result of x.await_resume()
153
//
154
//   (*) If x.await_suspend return type is bool, it allows to veto a suspend:
155
//      if (x.await_suspend(...))
156
//        llvm_coro_suspend();
157
//
158
//  (**) llvm_coro_suspend() encodes three possible continuations as
159
//       a switch instruction:
160
//
161
//  %where-to = call i8 @llvm.coro.suspend(...)
162
//  switch i8 %where-to, label %coro.ret [ ; jump to epilogue to suspend
163
//    i8 0, label %yield.ready   ; go here when resumed
164
//    i8 1, label %yield.cleanup ; go here when destroyed
165
//  ]
166
//
167
//  See llvm's docs/Coroutines.rst for more details.
168
//
169
namespace {
170
  struct LValueOrRValue {
171
    LValue LV;
172
    RValue RV;
173
  };
174
}
175
static LValueOrRValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro,
176
                                    CoroutineSuspendExpr const &S,
177
                                    AwaitKind Kind, AggValueSlot aggSlot,
178
110
                                    bool ignoreResult, bool forLValue) {
179
110
  auto *E = S.getCommonExpr();
180
110
181
110
  auto Binder =
182
110
      CodeGenFunction::OpaqueValueMappingData::bind(CGF, S.getOpaqueValue(), E);
183
110
  auto UnbindOnExit = llvm::make_scope_exit([&] { Binder.unbind(CGF); });
184
110
185
110
  auto Prefix = buildSuspendPrefixStr(Coro, Kind);
186
110
  BasicBlock *ReadyBlock = CGF.createBasicBlock(Prefix + Twine(".ready"));
187
110
  BasicBlock *SuspendBlock = CGF.createBasicBlock(Prefix + Twine(".suspend"));
188
110
  BasicBlock *CleanupBlock = CGF.createBasicBlock(Prefix + Twine(".cleanup"));
189
110
190
110
  // If expression is ready, no need to suspend.
191
110
  CGF.EmitBranchOnBoolExpr(S.getReadyExpr(), ReadyBlock, SuspendBlock, 0);
192
110
193
110
  // Otherwise, emit suspend logic.
194
110
  CGF.EmitBlock(SuspendBlock);
195
110
196
110
  auto &Builder = CGF.Builder;
197
110
  llvm::Function *CoroSave = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_save);
198
110
  auto *NullPtr = llvm::ConstantPointerNull::get(CGF.CGM.Int8PtrTy);
199
110
  auto *SaveCall = Builder.CreateCall(CoroSave, {NullPtr});
200
110
201
110
  auto *SuspendRet = CGF.EmitScalarExpr(S.getSuspendExpr());
202
110
  if (SuspendRet != nullptr && 
SuspendRet->getType()->isIntegerTy(1)3
) {
203
2
    // Veto suspension if requested by bool returning await_suspend.
204
2
    BasicBlock *RealSuspendBlock =
205
2
        CGF.createBasicBlock(Prefix + Twine(".suspend.bool"));
206
2
    CGF.Builder.CreateCondBr(SuspendRet, RealSuspendBlock, ReadyBlock);
207
2
    CGF.EmitBlock(RealSuspendBlock);
208
2
  }
209
110
210
110
  // Emit the suspend point.
211
110
  const bool IsFinalSuspend = (Kind == AwaitKind::Final);
212
110
  llvm::Function *CoroSuspend =
213
110
      CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_suspend);
214
110
  auto *SuspendResult = Builder.CreateCall(
215
110
      CoroSuspend, {SaveCall, Builder.getInt1(IsFinalSuspend)});
216
110
217
110
  // Create a switch capturing three possible continuations.
218
110
  auto *Switch = Builder.CreateSwitch(SuspendResult, Coro.SuspendBB, 2);
219
110
  Switch->addCase(Builder.getInt8(0), ReadyBlock);
220
110
  Switch->addCase(Builder.getInt8(1), CleanupBlock);
221
110
222
110
  // Emit cleanup for this suspend point.
223
110
  CGF.EmitBlock(CleanupBlock);
224
110
  CGF.EmitBranchThroughCleanup(Coro.CleanupJD);
225
110
226
110
  // Emit await_resume expression.
227
110
  CGF.EmitBlock(ReadyBlock);
228
110
229
110
  // Exception handling requires additional IR. If the 'await_resume' function
230
110
  // is marked as 'noexcept', we avoid generating this additional IR.
231
110
  CXXTryStmt *TryStmt = nullptr;
232
110
  if (Coro.ExceptionHandler && 
Kind == AwaitKind::Init21
&&
233
110
      
memberCallExpressionCanThrow(S.getResumeExpr())10
) {
234
4
    Coro.ResumeEHVar =
235
4
        CGF.CreateTempAlloca(Builder.getInt1Ty(), Prefix + Twine("resume.eh"));
236
4
    Builder.CreateFlagStore(true, Coro.ResumeEHVar);
237
4
238
4
    auto Loc = S.getResumeExpr()->getExprLoc();
239
4
    auto *Catch = new (CGF.getContext())
240
4
        CXXCatchStmt(Loc, /*exDecl=*/nullptr, Coro.ExceptionHandler);
241
4
    auto *TryBody =
242
4
        CompoundStmt::Create(CGF.getContext(), S.getResumeExpr(), Loc, Loc);
243
4
    TryStmt = CXXTryStmt::Create(CGF.getContext(), Loc, TryBody, Catch);
244
4
    CGF.EnterCXXTryStmt(*TryStmt);
245
4
  }
246
110
247
110
  LValueOrRValue Res;
248
110
  if (forLValue)
249
3
    Res.LV = CGF.EmitLValue(S.getResumeExpr());
250
107
  else
251
107
    Res.RV = CGF.EmitAnyExpr(S.getResumeExpr(), aggSlot, ignoreResult);
252
110
253
110
  if (TryStmt) {
254
4
    Builder.CreateFlagStore(false, Coro.ResumeEHVar);
255
4
    CGF.ExitCXXTryStmt(*TryStmt);
256
4
  }
257
110
258
110
  return Res;
259
110
}
260
261
RValue CodeGenFunction::EmitCoawaitExpr(const CoawaitExpr &E,
262
                                        AggValueSlot aggSlot,
263
106
                                        bool ignoreResult) {
264
106
  return emitSuspendExpression(*this, *CurCoro.Data, E,
265
106
                               CurCoro.Data->CurrentAwaitKind, aggSlot,
266
106
                               ignoreResult, /*forLValue*/false).RV;
267
106
}
268
RValue CodeGenFunction::EmitCoyieldExpr(const CoyieldExpr &E,
269
                                        AggValueSlot aggSlot,
270
1
                                        bool ignoreResult) {
271
1
  return emitSuspendExpression(*this, *CurCoro.Data, E, AwaitKind::Yield,
272
1
                               aggSlot, ignoreResult, /*forLValue*/false).RV;
273
1
}
274
275
42
void CodeGenFunction::EmitCoreturnStmt(CoreturnStmt const &S) {
276
42
  ++CurCoro.Data->CoreturnCount;
277
42
  const Expr *RV = S.getOperand();
278
42
  if (RV && 
RV->getType()->isVoidType()3
) {
279
1
    // Make sure to evaluate the expression of a co_return with a void
280
1
    // expression for side effects.
281
1
    RunCleanupsScope cleanupScope(*this);
282
1
    EmitIgnoredExpr(RV);
283
1
  }
284
42
  EmitStmt(S.getPromiseCall());
285
42
  EmitBranchThroughCleanup(CurCoro.Data->FinalJD);
286
42
}
287
288
289
#ifndef NDEBUG
290
static QualType getCoroutineSuspendExprReturnType(const ASTContext &Ctx,
291
3
  const CoroutineSuspendExpr *E) {
292
3
  const auto *RE = E->getResumeExpr();
293
3
  // Is it possible for RE to be a CXXBindTemporaryExpr wrapping
294
3
  // a MemberCallExpr?
295
3
  assert(isa<CallExpr>(RE) && "unexpected suspend expression type");
296
3
  return cast<CallExpr>(RE)->getCallReturnType(Ctx);
297
3
}
298
#endif
299
300
LValue
301
2
CodeGenFunction::EmitCoawaitLValue(const CoawaitExpr *E) {
302
2
  assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
303
2
         "Can't have a scalar return unless the return type is a "
304
2
         "reference type!");
305
2
  return emitSuspendExpression(*this, *CurCoro.Data, *E,
306
2
                               CurCoro.Data->CurrentAwaitKind, AggValueSlot::ignored(),
307
2
                               /*ignoreResult*/false, /*forLValue*/true).LV;
308
2
}
309
310
LValue
311
1
CodeGenFunction::EmitCoyieldLValue(const CoyieldExpr *E) {
312
1
  assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
313
1
         "Can't have a scalar return unless the return type is a "
314
1
         "reference type!");
315
1
  return emitSuspendExpression(*this, *CurCoro.Data, *E,
316
1
                               AwaitKind::Yield, AggValueSlot::ignored(),
317
1
                               /*ignoreResult*/false, /*forLValue*/true).LV;
318
1
}
319
320
// Hunts for the parameter reference in the parameter copy/move declaration.
321
namespace {
322
struct GetParamRef : public StmtVisitor<GetParamRef> {
323
public:
324
  DeclRefExpr *Expr = nullptr;
325
28
  GetParamRef() {}
326
28
  void VisitDeclRefExpr(DeclRefExpr *E) {
327
28
    assert(Expr == nullptr && "multilple declref in param move");
328
28
    Expr = E;
329
28
  }
330
42
  void VisitStmt(Stmt *S) {
331
42
    for (auto *C : S->children()) {
332
42
      if (C)
333
42
        Visit(C);
334
42
    }
335
42
  }
336
};
337
}
338
339
// This class replaces references to parameters to their copies by changing
340
// the addresses in CGF.LocalDeclMap and restoring back the original values in
341
// its destructor.
342
343
namespace {
344
  struct ParamReferenceReplacerRAII {
345
    CodeGenFunction::DeclMapTy SavedLocals;
346
    CodeGenFunction::DeclMapTy& LocalDeclMap;
347
348
    ParamReferenceReplacerRAII(CodeGenFunction::DeclMapTy &LocalDeclMap)
349
44
        : LocalDeclMap(LocalDeclMap) {}
350
351
28
    void addCopy(DeclStmt const *PM) {
352
28
      // Figure out what param it refers to.
353
28
354
28
      assert(PM->isSingleDecl());
355
28
      VarDecl const*VD = static_cast<VarDecl const*>(PM->getSingleDecl());
356
28
      Expr const *InitExpr = VD->getInit();
357
28
      GetParamRef Visitor;
358
28
      Visitor.Visit(const_cast<Expr*>(InitExpr));
359
28
      assert(Visitor.Expr);
360
28
      DeclRefExpr *DREOrig = Visitor.Expr;
361
28
      auto *PD = DREOrig->getDecl();
362
28
363
28
      auto it = LocalDeclMap.find(PD);
364
28
      assert(it != LocalDeclMap.end() && "parameter is not found");
365
28
      SavedLocals.insert({ PD, it->second });
366
28
367
28
      auto copyIt = LocalDeclMap.find(VD);
368
28
      assert(copyIt != LocalDeclMap.end() && "parameter copy is not found");
369
28
      it->second = copyIt->getSecond();
370
28
    }
371
372
44
    ~ParamReferenceReplacerRAII() {
373
44
      for (auto&& SavedLocal : SavedLocals) {
374
28
        LocalDeclMap.insert({SavedLocal.first, SavedLocal.second});
375
28
      }
376
44
    }
377
  };
378
}
379
380
// For WinEH exception representation backend needs to know what funclet coro.end
381
// belongs to. That information is passed in a funclet bundle.
382
static SmallVector<llvm::OperandBundleDef, 1>
383
11
getBundlesForCoroEnd(CodeGenFunction &CGF) {
384
11
  SmallVector<llvm::OperandBundleDef, 1> BundleList;
385
11
386
11
  if (llvm::Instruction *EHPad = CGF.CurrentFuncletPad)
387
3
    BundleList.emplace_back("funclet", EHPad);
388
11
389
11
  return BundleList;
390
11
}
391
392
namespace {
393
// We will insert coro.end to cut any of the destructors for objects that
394
// do not need to be destroyed once the coroutine is resumed.
395
// See llvm/docs/Coroutines.rst for more details about coro.end.
396
struct CallCoroEnd final : public EHScopeStack::Cleanup {
397
11
  void Emit(CodeGenFunction &CGF, Flags flags) override {
398
11
    auto &CGM = CGF.CGM;
399
11
    auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
400
11
    llvm::Function *CoroEndFn = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
401
11
    // See if we have a funclet bundle to associate coro.end with. (WinEH)
402
11
    auto Bundles = getBundlesForCoroEnd(CGF);
403
11
    auto *CoroEnd = CGF.Builder.CreateCall(
404
11
        CoroEndFn, {NullPtr, CGF.Builder.getTrue()}, Bundles);
405
11
    if (Bundles.empty()) {
406
8
      // Otherwise, (landingpad model), create a conditional branch that leads
407
8
      // either to a cleanup block or a block with EH resume instruction.
408
8
      auto *ResumeBB = CGF.getEHResumeBlock(/*isCleanup=*/true);
409
8
      auto *CleanupContBB = CGF.createBasicBlock("cleanup.cont");
410
8
      CGF.Builder.CreateCondBr(CoroEnd, ResumeBB, CleanupContBB);
411
8
      CGF.EmitBlock(CleanupContBB);
412
8
    }
413
11
  }
414
};
415
}
416
417
namespace {
418
// Make sure to call coro.delete on scope exit.
419
struct CallCoroDelete final : public EHScopeStack::Cleanup {
420
  Stmt *Deallocate;
421
422
  // Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;"
423
424
  // Note: That deallocation will be emitted twice: once for a normal exit and
425
  // once for exceptional exit. This usage is safe because Deallocate does not
426
  // contain any declarations. The SubStmtBuilder::makeNewAndDeleteExpr()
427
  // builds a single call to a deallocation function which is safe to emit
428
  // multiple times.
429
58
  void Emit(CodeGenFunction &CGF, Flags) override {
430
58
    // Remember the current point, as we are going to emit deallocation code
431
58
    // first to get to coro.free instruction that is an argument to a delete
432
58
    // call.
433
58
    BasicBlock *SaveInsertBlock = CGF.Builder.GetInsertBlock();
434
58
435
58
    auto *FreeBB = CGF.createBasicBlock("coro.free");
436
58
    CGF.EmitBlock(FreeBB);
437
58
    CGF.EmitStmt(Deallocate);
438
58
439
58
    auto *AfterFreeBB = CGF.createBasicBlock("after.coro.free");
440
58
    CGF.EmitBlock(AfterFreeBB);
441
58
442
58
    // We should have captured coro.free from the emission of deallocate.
443
58
    auto *CoroFree = CGF.CurCoro.Data->LastCoroFree;
444
58
    if (!CoroFree) {
445
0
      CGF.CGM.Error(Deallocate->getBeginLoc(),
446
0
                    "Deallocation expressoin does not refer to coro.free");
447
0
      return;
448
0
    }
449
58
450
58
    // Get back to the block we were originally and move coro.free there.
451
58
    auto *InsertPt = SaveInsertBlock->getTerminator();
452
58
    CoroFree->moveBefore(InsertPt);
453
58
    CGF.Builder.SetInsertPoint(InsertPt);
454
58
455
58
    // Add if (auto *mem = coro.free) Deallocate;
456
58
    auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
457
58
    auto *Cond = CGF.Builder.CreateICmpNE(CoroFree, NullPtr);
458
58
    CGF.Builder.CreateCondBr(Cond, FreeBB, AfterFreeBB);
459
58
460
58
    // No longer need old terminator.
461
58
    InsertPt->eraseFromParent();
462
58
    CGF.Builder.SetInsertPoint(AfterFreeBB);
463
58
  }
464
44
  explicit CallCoroDelete(Stmt *DeallocStmt) : Deallocate(DeallocStmt) {}
465
};
466
}
467
468
namespace {
469
struct GetReturnObjectManager {
470
  CodeGenFunction &CGF;
471
  CGBuilderTy &Builder;
472
  const CoroutineBodyStmt &S;
473
474
  Address GroActiveFlag;
475
  CodeGenFunction::AutoVarEmission GroEmission;
476
477
  GetReturnObjectManager(CodeGenFunction &CGF, const CoroutineBodyStmt &S)
478
      : CGF(CGF), Builder(CGF.Builder), S(S), GroActiveFlag(Address::invalid()),
479
44
        GroEmission(CodeGenFunction::AutoVarEmission::invalid()) {}
480
481
  // The gro variable has to outlive coroutine frame and coroutine promise, but,
482
  // it can only be initialized after coroutine promise was created, thus, we
483
  // split its emission in two parts. EmitGroAlloca emits an alloca and sets up
484
  // cleanups. Later when coroutine promise is available we initialize the gro
485
  // and sets the flag that the cleanup is now active.
486
487
44
  void EmitGroAlloca() {
488
44
    auto *GroDeclStmt = dyn_cast<DeclStmt>(S.getResultDecl());
489
44
    if (!GroDeclStmt) {
490
24
      // If get_return_object returns void, no need to do an alloca.
491
24
      return;
492
24
    }
493
20
494
20
    auto *GroVarDecl = cast<VarDecl>(GroDeclStmt->getSingleDecl());
495
20
496
20
    // Set GRO flag that it is not initialized yet
497
20
    GroActiveFlag =
498
20
      CGF.CreateTempAlloca(Builder.getInt1Ty(), CharUnits::One(), "gro.active");
499
20
    Builder.CreateStore(Builder.getFalse(), GroActiveFlag);
500
20
501
20
    GroEmission = CGF.EmitAutoVarAlloca(*GroVarDecl);
502
20
503
20
    // Remember the top of EHStack before emitting the cleanup.
504
20
    auto old_top = CGF.EHStack.stable_begin();
505
20
    CGF.EmitAutoVarCleanups(GroEmission);
506
20
    auto top = CGF.EHStack.stable_begin();
507
20
508
20
    // Make the cleanup conditional on gro.active
509
20
    for (auto b = CGF.EHStack.find(top), e = CGF.EHStack.find(old_top);
510
22
      b != e; 
b++2
) {
511
2
      if (auto *Cleanup = dyn_cast<EHCleanupScope>(&*b)) {
512
2
        assert(!Cleanup->hasActiveFlag() && "cleanup already has active flag?");
513
2
        Cleanup->setActiveFlag(GroActiveFlag);
514
2
        Cleanup->setTestFlagInEHCleanup();
515
2
        Cleanup->setTestFlagInNormalCleanup();
516
2
      }
517
2
    }
518
20
  }
519
520
44
  void EmitGroInit() {
521
44
    if (!GroActiveFlag.isValid()) {
522
24
      // No Gro variable was allocated. Simply emit the call to
523
24
      // get_return_object.
524
24
      CGF.EmitStmt(S.getResultDecl());
525
24
      return;
526
24
    }
527
20
528
20
    CGF.EmitAutoVarInit(GroEmission);
529
20
    Builder.CreateStore(Builder.getTrue(), GroActiveFlag);
530
20
  }
531
};
532
}
533
534
static void emitBodyAndFallthrough(CodeGenFunction &CGF,
535
44
                                   const CoroutineBodyStmt &S, Stmt *Body) {
536
44
  CGF.EmitStmt(Body);
537
44
  const bool CanFallthrough = CGF.Builder.GetInsertBlock();
538
44
  if (CanFallthrough)
539
13
    if (Stmt *OnFallthrough = S.getFallthroughHandler())
540
13
      CGF.EmitStmt(OnFallthrough);
541
44
}
542
543
44
void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt &S) {
544
44
  auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
545
44
  auto &TI = CGM.getContext().getTargetInfo();
546
44
  unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();
547
44
548
44
  auto *EntryBB = Builder.GetInsertBlock();
549
44
  auto *AllocBB = createBasicBlock("coro.alloc");
550
44
  auto *InitBB = createBasicBlock("coro.init");
551
44
  auto *FinalBB = createBasicBlock("coro.final");
552
44
  auto *RetBB = createBasicBlock("coro.ret");
553
44
554
44
  auto *CoroId = Builder.CreateCall(
555
44
      CGM.getIntrinsic(llvm::Intrinsic::coro_id),
556
44
      {Builder.getInt32(NewAlign), NullPtr, NullPtr, NullPtr});
557
44
  createCoroData(*this, CurCoro, CoroId);
558
44
  CurCoro.Data->SuspendBB = RetBB;
559
44
560
44
  // Backend is allowed to elide memory allocations, to help it, emit
561
44
  // auto mem = coro.alloc() ? 0 : ... allocation code ...;
562
44
  auto *CoroAlloc = Builder.CreateCall(
563
44
      CGM.getIntrinsic(llvm::Intrinsic::coro_alloc), {CoroId});
564
44
565
44
  Builder.CreateCondBr(CoroAlloc, AllocBB, InitBB);
566
44
567
44
  EmitBlock(AllocBB);
568
44
  auto *AllocateCall = EmitScalarExpr(S.getAllocate());
569
44
  auto *AllocOrInvokeContBB = Builder.GetInsertBlock();
570
44
571
44
  // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
572
44
  if (auto *RetOnAllocFailure = S.getReturnStmtOnAllocFailure()) {
573
2
    auto *RetOnFailureBB = createBasicBlock("coro.ret.on.failure");
574
2
575
2
    // See if allocation was successful.
576
2
    auto *NullPtr = llvm::ConstantPointerNull::get(Int8PtrTy);
577
2
    auto *Cond = Builder.CreateICmpNE(AllocateCall, NullPtr);
578
2
    Builder.CreateCondBr(Cond, InitBB, RetOnFailureBB);
579
2
580
2
    // If not, return OnAllocFailure object.
581
2
    EmitBlock(RetOnFailureBB);
582
2
    EmitStmt(RetOnAllocFailure);
583
2
  }
584
42
  else {
585
42
    Builder.CreateBr(InitBB);
586
42
  }
587
44
588
44
  EmitBlock(InitBB);
589
44
590
44
  // Pass the result of the allocation to coro.begin.
591
44
  auto *Phi = Builder.CreatePHI(VoidPtrTy, 2);
592
44
  Phi->addIncoming(NullPtr, EntryBB);
593
44
  Phi->addIncoming(AllocateCall, AllocOrInvokeContBB);
594
44
  auto *CoroBegin = Builder.CreateCall(
595
44
      CGM.getIntrinsic(llvm::Intrinsic::coro_begin), {CoroId, Phi});
596
44
  CurCoro.Data->CoroBegin = CoroBegin;
597
44
598
44
  GetReturnObjectManager GroManager(*this, S);
599
44
  GroManager.EmitGroAlloca();
600
44
601
44
  CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(RetBB);
602
44
  {
603
44
    ParamReferenceReplacerRAII ParamReplacer(LocalDeclMap);
604
44
    CodeGenFunction::RunCleanupsScope ResumeScope(*this);
605
44
    EHStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, S.getDeallocate());
606
44
607
44
    // Create parameter copies. We do it before creating a promise, since an
608
44
    // evolution of coroutine TS may allow promise constructor to observe
609
44
    // parameter copies.
610
44
    for (auto *PM : S.getParamMoves()) {
611
28
      EmitStmt(PM);
612
28
      ParamReplacer.addCopy(cast<DeclStmt>(PM));
613
28
      // TODO: if(CoroParam(...)) need to surround ctor and dtor
614
28
      // for the copy, so that llvm can elide it if the copy is
615
28
      // not needed.
616
28
    }
617
44
618
44
    EmitStmt(S.getPromiseDeclStmt());
619
44
620
44
    Address PromiseAddr = GetAddrOfLocalVar(S.getPromiseDecl());
621
44
    auto *PromiseAddrVoidPtr =
622
44
        new llvm::BitCastInst(PromiseAddr.getPointer(), VoidPtrTy, "", CoroId);
623
44
    // Update CoroId to refer to the promise. We could not do it earlier because
624
44
    // promise local variable was not emitted yet.
625
44
    CoroId->setArgOperand(1, PromiseAddrVoidPtr);
626
44
627
44
    // Now we have the promise, initialize the GRO
628
44
    GroManager.EmitGroInit();
629
44
630
44
    EHStack.pushCleanup<CallCoroEnd>(EHCleanup);
631
44
632
44
    CurCoro.Data->CurrentAwaitKind = AwaitKind::Init;
633
44
    CurCoro.Data->ExceptionHandler = S.getExceptionHandler();
634
44
    EmitStmt(S.getInitSuspendStmt());
635
44
    CurCoro.Data->FinalJD = getJumpDestInCurrentScope(FinalBB);
636
44
637
44
    CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal;
638
44
639
44
    if (CurCoro.Data->ExceptionHandler) {
640
10
      // If we generated IR to record whether an exception was thrown from
641
10
      // 'await_resume', then use that IR to determine whether the coroutine
642
10
      // body should be skipped.
643
10
      // If we didn't generate the IR (perhaps because 'await_resume' was marked
644
10
      // as 'noexcept'), then we skip this check.
645
10
      BasicBlock *ContBB = nullptr;
646
10
      if (CurCoro.Data->ResumeEHVar) {
647
4
        BasicBlock *BodyBB = createBasicBlock("coro.resumed.body");
648
4
        ContBB = createBasicBlock("coro.resumed.cont");
649
4
        Value *SkipBody = Builder.CreateFlagLoad(CurCoro.Data->ResumeEHVar,
650
4
                                                 "coro.resumed.eh");
651
4
        Builder.CreateCondBr(SkipBody, ContBB, BodyBB);
652
4
        EmitBlock(BodyBB);
653
4
      }
654
10
655
10
      auto Loc = S.getBeginLoc();
656
10
      CXXCatchStmt Catch(Loc, /*exDecl=*/nullptr,
657
10
                         CurCoro.Data->ExceptionHandler);
658
10
      auto *TryStmt =
659
10
          CXXTryStmt::Create(getContext(), Loc, S.getBody(), &Catch);
660
10
661
10
      EnterCXXTryStmt(*TryStmt);
662
10
      emitBodyAndFallthrough(*this, S, TryStmt->getTryBlock());
663
10
      ExitCXXTryStmt(*TryStmt);
664
10
665
10
      if (ContBB)
666
4
        EmitBlock(ContBB);
667
10
    }
668
34
    else {
669
34
      emitBodyAndFallthrough(*this, S, S.getBody());
670
34
    }
671
44
672
44
    // See if we need to generate final suspend.
673
44
    const bool CanFallthrough = Builder.GetInsertBlock();
674
44
    const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0;
675
44
    if (CanFallthrough || 
HasCoreturns35
) {
676
42
      EmitBlock(FinalBB);
677
42
      CurCoro.Data->CurrentAwaitKind = AwaitKind::Final;
678
42
      EmitStmt(S.getFinalSuspendStmt());
679
42
    } else {
680
2
      // We don't need FinalBB. Emit it to make sure the block is deleted.
681
2
      EmitBlock(FinalBB, /*IsFinished=*/true);
682
2
    }
683
44
  }
684
44
685
44
  EmitBlock(RetBB);
686
44
  // Emit coro.end before getReturnStmt (and parameter destructors), since
687
44
  // resume and destroy parts of the coroutine should not include them.
688
44
  llvm::Function *CoroEnd = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
689
44
  Builder.CreateCall(CoroEnd, {NullPtr, Builder.getFalse()});
690
44
691
44
  if (Stmt *Ret = S.getReturnStmt())
692
20
    EmitStmt(Ret);
693
44
}
694
695
// Emit coroutine intrinsic and patch up arguments of the token type.
696
RValue CodeGenFunction::EmitCoroutineIntrinsic(const CallExpr *E,
697
250
                                               unsigned int IID) {
698
250
  SmallVector<llvm::Value *, 8> Args;
699
250
  switch (IID) {
700
11
  default:
701
11
    break;
702
0
  // The coro.frame builtin is replaced with an SSA value of the coro.begin
703
0
  // intrinsic.
704
174
  case llvm::Intrinsic::coro_frame: {
705
174
    if (CurCoro.Data && CurCoro.Data->CoroBegin) {
706
174
      return RValue::get(CurCoro.Data->CoroBegin);
707
174
    }
708
0
    CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_begin "
709
0
                                "has been used earlier in this function");
710
0
    auto NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
711
0
    return RValue::get(NullPtr);
712
0
  }
713
0
  // The following three intrinsics take a token parameter referring to a token
714
0
  // returned by earlier call to @llvm.coro.id. Since we cannot represent it in
715
0
  // builtins, we patch it up here.
716
64
  case llvm::Intrinsic::coro_alloc:
717
64
  case llvm::Intrinsic::coro_begin:
718
64
  case llvm::Intrinsic::coro_free: {
719
64
    if (CurCoro.Data && 
CurCoro.Data->CoroId61
) {
720
61
      Args.push_back(CurCoro.Data->CoroId);
721
61
      break;
722
61
    }
723
3
    CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_id has"
724
3
                                " been used earlier in this function");
725
3
    // Fallthrough to the next case to add TokenNone as the first argument.
726
3
    LLVM_FALLTHROUGH;
727
3
  }
728
3
  // @llvm.coro.suspend takes a token parameter. Add token 'none' as the first
729
3
  // argument.
730
4
  case llvm::Intrinsic::coro_suspend:
731
4
    Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
732
4
    break;
733
76
  }
734
76
  for (const Expr *Arg : E->arguments())
735
86
    Args.push_back(EmitScalarExpr(Arg));
736
76
737
76
  llvm::Function *F = CGM.getIntrinsic(IID);
738
76
  llvm::CallInst *Call = Builder.CreateCall(F, Args);
739
76
740
76
  // Note: The following code is to enable to emit coro.id and coro.begin by
741
76
  // hand to experiment with coroutines in C.
742
76
  // If we see @llvm.coro.id remember it in the CoroData. We will update
743
76
  // coro.alloc, coro.begin and coro.free intrinsics to refer to it.
744
76
  if (IID == llvm::Intrinsic::coro_id) {
745
3
    createCoroData(*this, CurCoro, Call, E);
746
3
  }
747
73
  else if (IID == llvm::Intrinsic::coro_begin) {
748
2
    if (CurCoro.Data)
749
1
      CurCoro.Data->CoroBegin = Call;
750
2
  }
751
71
  else if (IID == llvm::Intrinsic::coro_free) {
752
60
    // Remember the last coro_free as we need it to build the conditional
753
60
    // deletion of the coroutine frame.
754
60
    if (CurCoro.Data)
755
59
      CurCoro.Data->LastCoroFree = Call;
756
60
  }
757
76
  return RValue::get(Call);
758
76
}