[Coroutines] Optimize the lifespan of temporary co_await object
authorXun Li <xun@fb.com>
Sun, 21 Jun 2020 03:29:10 +0000 (20:29 -0700)
committerXun Li <xun@fb.com>
Sun, 28 Jun 2020 17:18:15 +0000 (10:18 -0700)
commitc8755b6378c2a1f32d9a90bad6c56a1cc5a830c3
tree8c9f8cc6097cfcf6cdefc994d6a05da1bda66dea
parent931411136af6061a7a48553344ff750d2a362d68
[Coroutines] Optimize the lifespan of temporary co_await object

Summary:
If we ever assign co_await to a temporary variable, such as foo(co_await expr),
we generate AST that looks like this: MaterializedTemporaryExpr(CoawaitExpr(...)).
MaterializedTemporaryExpr would emit an intrinsics that marks the lifetime start of the
temporary storage. However such temporary storage will not be used until co_await is ready
to write the result. Marking the lifetime start way too early causes extra storage to be
put in the coroutine frame instead of the stack.
As you can see from https://godbolt.org/z/zVx_eB, the frame generated for get_big_object2 is 12K, which contains a big_object object unnecessarily.
After this patch, the frame size for get_big_object2 is now only 8K. There are still room for improvements, in particular, GCC has a 4K frame for this function. But that's a separate problem and not addressed in this patch.

The basic idea of this patch is during CoroSplit, look for every local variable in the coroutine created through AllocaInst, identify all the lifetime start/end markers and the use of the variables, and sink the lifetime.start maker to the places as close to the first-ever use as possible.

Reviewers: lewissbaker, modocache, junparser

Reviewed By: junparser

Subscribers: hiraditya, llvm-commits, rsmith, ChuanqiXu, cfe-commits

Tags: #clang, #llvm

Differential Revision: https://reviews.llvm.org/D82314
llvm/lib/Transforms/Coroutines/CoroSplit.cpp
llvm/test/Transforms/Coroutines/coro-split-02.ll
llvm/test/Transforms/Coroutines/coro-split-sink-lifetime.ll [new file with mode: 0644]