blob: 6440b8cfb6c8f5c2f601f08c87c32ac22ea04d58 [file] [log] [blame]
David Majnemera6539272016-07-23 04:05:08 +00001=====================================
2Coroutines in LLVM
3=====================================
4
5.. contents::
6 :local:
7 :depth: 3
8
9.. warning::
10 This is a work in progress. Compatibility across LLVM releases is not
11 guaranteed.
12
13Introduction
14============
15
16.. _coroutine handle:
17
18LLVM coroutines are functions that have one or more `suspend points`_.
19When a suspend point is reached, the execution of a coroutine is suspended and
20control is returned back to its caller. A suspended coroutine can be resumed
21to continue execution from the last suspend point or it can be destroyed.
22
23In the following example, we call function `f` (which may or may not be a
24coroutine itself) that returns a handle to a suspended coroutine
25(**coroutine handle**) that is used by `main` to resume the coroutine twice and
26then destroy it:
27
28.. code-block:: llvm
29
30 define i32 @main() {
31 entry:
32 %hdl = call i8* @f(i32 4)
33 call void @llvm.coro.resume(i8* %hdl)
34 call void @llvm.coro.resume(i8* %hdl)
35 call void @llvm.coro.destroy(i8* %hdl)
36 ret i32 0
37 }
38
39.. _coroutine frame:
40
41In addition to the function stack frame which exists when a coroutine is
42executing, there is an additional region of storage that contains objects that
43keep the coroutine state when a coroutine is suspended. This region of storage
44is called **coroutine frame**. It is created when a coroutine is called and
45destroyed when a coroutine runs to completion or destroyed by a call to
46the `coro.destroy`_ intrinsic.
47
48An LLVM coroutine is represented as an LLVM function that has calls to
49`coroutine intrinsics`_ defining the structure of the coroutine.
50After lowering, a coroutine is split into several
51functions that represent three different ways of how control can enter the
52coroutine:
53
541. a ramp function, which represents an initial invocation of the coroutine that
55 creates the coroutine frame and executes the coroutine code until it
56 encounters a suspend point or reaches the end of the function;
57
582. a coroutine resume function that is invoked when the coroutine is resumed;
59
603. a coroutine destroy function that is invoked when the coroutine is destroyed.
61
62.. note:: Splitting out resume and destroy functions are just one of the
63 possible ways of lowering the coroutine. We chose it for initial
64 implementation as it matches closely the mental model and results in
65 reasonably nice code.
66
67Coroutines by Example
68=====================
69
70Coroutine Representation
71------------------------
72
73Let's look at an example of an LLVM coroutine with the behavior sketched
74by the following pseudo-code.
75
76.. code-block:: C++
77
78 void *f(int n) {
79 for(;;) {
80 print(n++);
81 <suspend> // returns a coroutine handle on first suspend
82 }
83 }
84
85This coroutine calls some function `print` with value `n` as an argument and
86suspends execution. Every time this coroutine resumes, it calls `print` again with an argument one bigger than the last time. This coroutine never completes by itself and must be destroyed explicitly. If we use this coroutine with
87a `main` shown in the previous section. It will call `print` with values 4, 5
88and 6 after which the coroutine will be destroyed.
89
90The LLVM IR for this coroutine looks like this:
91
Aaron Ballman378ac7e2016-07-23 18:53:35 +000092.. code-block:: none
David Majnemera6539272016-07-23 04:05:08 +000093
94 define i8* @f(i32 %n) {
95 entry:
96 %size = call i32 @llvm.coro.size.i32()
97 %alloc = call i8* @malloc(i32 %size)
98 %hdl = call noalias i8* @llvm.coro.begin(i8* %alloc, i32 0, i8* null, i8* null)
99 br label %loop
100 loop:
101 %n.val = phi i32 [ %n, %entry ], [ %inc, %loop ]
102 %inc = add nsw i32 %n.val, 1
103 call void @print(i32 %n.val)
104 %0 = call i8 @llvm.coro.suspend(token none, i1 false)
105 switch i8 %0, label %suspend [i8 0, label %loop
106 i8 1, label %cleanup]
107 cleanup:
108 %mem = call i8* @llvm.coro.free(i8* %hdl)
109 call void @free(i8* %mem)
110 br label %suspend
111 suspend:
112 call void @llvm.coro.end(i8* %hdl, i1 false)
113 ret i8* %hdl
114 }
115
116The `entry` block establishes the coroutine frame. The `coro.size`_ intrinsic is
117lowered to a constant representing the size required for the coroutine frame.
118The `coro.begin`_ intrinsic initializes the coroutine frame and returns the
119coroutine handle. The first parameter of `coro.begin` is given a block of memory
120to be used if the coroutine frame needs to be allocated dynamically.
121
122The `cleanup` block destroys the coroutine frame. The `coro.free`_ intrinsic,
123given the coroutine handle, returns a pointer of the memory block to be freed or
124`null` if the coroutine frame was not allocated dynamically. The `cleanup`
125block is entered when coroutine runs to completion by itself or destroyed via
126call to the `coro.destroy`_ intrinsic.
127
128The `suspend` block contains code to be executed when coroutine runs to
129completion or suspended. The `coro.end`_ intrinsic marks the point where
130a coroutine needs to return control back to the caller if it is not an initial
131invocation of the coroutine.
132
133The `loop` blocks represents the body of the coroutine. The `coro.suspend`_
134intrinsic in combination with the following switch indicates what happens to
135control flow when a coroutine is suspended (default case), resumed (case 0) or
136destroyed (case 1).
137
138Coroutine Transformation
139------------------------
140
141One of the steps of coroutine lowering is building the coroutine frame. The
142def-use chains are analyzed to determine which objects need be kept alive across
143suspend points. In the coroutine shown in the previous section, use of virtual register
144`%n.val` is separated from the definition by a suspend point, therefore, it
145cannot reside on the stack frame since the latter goes away once the coroutine
146is suspended and control is returned back to the caller. An i32 slot is
147allocated in the coroutine frame and `%n.val` is spilled and reloaded from that
148slot as needed.
149
150We also store addresses of the resume and destroy functions so that the
151`coro.resume` and `coro.destroy` intrinsics can resume and destroy the coroutine
152when its identity cannot be determined statically at compile time. For our
153example, the coroutine frame will be:
154
155.. code-block:: llvm
156
157 %f.frame = type { void (%f.frame*)*, void (%f.frame*)*, i32 }
158
159After resume and destroy parts are outlined, function `f` will contain only the
160code responsible for creation and initialization of the coroutine frame and
161execution of the coroutine until a suspend point is reached:
162
163.. code-block:: llvm
164
165 define i8* @f(i32 %n) {
166 entry:
167 %alloc = call noalias i8* @malloc(i32 24)
168 %0 = call noalias i8* @llvm.coro.begin(i8* %alloc, i32 0, i8* null, i8* null)
169 %frame = bitcast i8* %frame to %f.frame*
170 %1 = getelementptr %f.frame, %f.frame* %frame, i32 0, i32 0
171 store void (%f.frame*)* @f.resume, void (%f.frame*)** %1
172 %2 = getelementptr %f.frame, %f.frame* %frame, i32 0, i32 1
173 store void (%f.frame*)* @f.destroy, void (%f.frame*)** %2
174
175 %inc = add nsw i32 %n, 1
176 %inc.spill.addr = getelementptr inbounds %f.Frame, %f.Frame* %FramePtr, i32 0, i32 2
177 store i32 %inc, i32* %inc.spill.addr
178 call void @print(i32 %n)
179
180 ret i8* %frame
181 }
182
183Outlined resume part of the coroutine will reside in function `f.resume`:
184
185.. code-block:: llvm
186
187 define internal fastcc void @f.resume(%f.frame* %frame.ptr.resume) {
188 entry:
189 %inc.spill.addr = getelementptr %f.frame, %f.frame* %frame.ptr.resume, i64 0, i32 2
190 %inc.spill = load i32, i32* %inc.spill.addr, align 4
191 %inc = add i32 %n.val, 1
192 store i32 %inc, i32* %inc.spill.addr, align 4
193 tail call void @print(i32 %inc)
194 ret void
195 }
196
197Whereas function `f.destroy` will contain the cleanup code for the coroutine:
198
199.. code-block:: llvm
200
201 define internal fastcc void @f.destroy(%f.frame* %frame.ptr.destroy) {
202 entry:
203 %0 = bitcast %f.frame* %frame.ptr.destroy to i8*
204 tail call void @free(i8* %0)
205 ret void
206 }
207
208Avoiding Heap Allocations
209-------------------------
210
211A particular coroutine usage pattern, which is illustrated by the `main`
212function in the overview section, where a coroutine is created, manipulated and
213destroyed by the same calling function, is common for coroutines implementing
214RAII idiom and is suitable for allocation elision optimization which avoid
215dynamic allocation by storing the coroutine frame as a static `alloca` in its
216caller.
217
218If a coroutine uses allocation and deallocation functions that are known to
219LLVM, unused calls to `malloc` and calls to `free` with `null` argument will be
220removed as dead code. However, if custom allocation functions are used, the
221`coro.alloc` and `coro.free` intrinsics can be used to enable removal of custom
222allocation and deallocation code when coroutine does not require dynamic
223allocation of the coroutine frame.
224
225In the entry block, we will call `coro.alloc`_ intrinsic that will return `null`
226when dynamic allocation is required, and non-null otherwise:
227
228.. code-block:: llvm
229
230 entry:
231 %elide = call i8* @llvm.coro.alloc()
232 %need.dyn.alloc = icmp ne i8* %elide, null
233 br i1 %need.dyn.alloc, label %coro.begin, label %dyn.alloc
234 dyn.alloc:
235 %size = call i32 @llvm.coro.size.i32()
236 %alloc = call i8* @CustomAlloc(i32 %size)
237 br label %coro.begin
238 coro.begin:
239 %phi = phi i8* [ %elide, %entry ], [ %alloc, %dyn.alloc ]
240 %hdl = call noalias i8* @llvm.coro.begin(i8* %phi, i32 0, i8* null, i8* null)
241
242In the cleanup block, we will make freeing the coroutine frame conditional on
243`coro.free`_ intrinsic. If allocation is elided, `coro.free`_ returns `null`
244thus skipping the deallocation code:
245
246.. code-block:: llvm
247
248 cleanup:
249 %mem = call i8* @llvm.coro.free(i8* %hdl)
250 %need.dyn.free = icmp ne i8* %mem, null
251 br i1 %need.dyn.free, label %dyn.free, label %if.end
252 dyn.free:
253 call void @CustomFree(i8* %mem)
254 br label %if.end
255 if.end:
256 ...
257
258With allocations and deallocations represented as described as above, after
259coroutine heap allocation elision optimization, the resulting main will end up
260looking just like it was when we used `malloc` and `free`:
261
262.. code-block:: llvm
263
264 define i32 @main() {
265 entry:
266 call void @print(i32 4)
267 call void @print(i32 5)
268 call void @print(i32 6)
269 ret i32 0
270 }
271
272Multiple Suspend Points
273-----------------------
274
275Let's consider the coroutine that has more than one suspend point:
276
277.. code-block:: C++
278
279 void *f(int n) {
280 for(;;) {
281 print(n++);
282 <suspend>
283 print(-n);
284 <suspend>
285 }
286 }
287
288Matching LLVM code would look like (with the rest of the code remaining the same
289as the code in the previous section):
290
291.. code-block:: llvm
292
293 loop:
294 %n.addr = phi i32 [ %n, %entry ], [ %inc, %loop.resume ]
295 call void @print(i32 %n.addr) #4
296 %2 = call i8 @llvm.coro.suspend(token none, i1 false)
297 switch i8 %2, label %suspend [i8 0, label %loop.resume
298 i8 1, label %cleanup]
299 loop.resume:
300 %inc = add nsw i32 %n.addr, 1
301 %sub = xor i32 %n.addr, -1
302 call void @print(i32 %sub)
303 %3 = call i8 @llvm.coro.suspend(token none, i1 false)
304 switch i8 %3, label %suspend [i8 0, label %loop
305 i8 1, label %cleanup]
306
307In this case, the coroutine frame would include a suspend index that will
308indicate at which suspend point the coroutine needs to resume. The resume
309function will use an index to jump to an appropriate basic block and will look
310as follows:
311
312.. code-block:: llvm
313
314 define internal fastcc void @f.Resume(%f.Frame* %FramePtr) {
315 entry.Resume:
316 %index.addr = getelementptr inbounds %f.Frame, %f.Frame* %FramePtr, i64 0, i32 2
317 %index = load i8, i8* %index.addr, align 1
318 %switch = icmp eq i8 %index, 0
319 %n.addr = getelementptr inbounds %f.Frame, %f.Frame* %FramePtr, i64 0, i32 3
320 %n = load i32, i32* %n.addr, align 4
321 br i1 %switch, label %loop.resume, label %loop
322
323 loop.resume:
324 %sub = xor i32 %n, -1
325 call void @print(i32 %sub)
326 br label %suspend
327 loop:
328 %inc = add nsw i32 %n, 1
329 store i32 %inc, i32* %n.addr, align 4
330 tail call void @print(i32 %inc)
331 br label %suspend
332
333 suspend:
334 %storemerge = phi i8 [ 0, %loop ], [ 1, %loop.resume ]
335 store i8 %storemerge, i8* %index.addr, align 1
336 ret void
337 }
338
339If different cleanup code needs to get executed for different suspend points,
340a similar switch will be in the `f.destroy` function.
341
342.. note ::
343
344 Using suspend index in a coroutine state and having a switch in `f.resume` and
345 `f.destroy` is one of the possible implementation strategies. We explored
346 another option where a distinct `f.resume1`, `f.resume2`, etc. are created for
347 every suspend point, and instead of storing an index, the resume and destroy
348 function pointers are updated at every suspend. Early testing showed that the
349 current approach is easier on the optimizer than the latter so it is a
350 lowering strategy implemented at the moment.
351
352Distinct Save and Suspend
353-------------------------
354
355In the previous example, setting a resume index (or some other state change that
356needs to happen to prepare a coroutine for resumption) happens at the same time as
357a suspension of a coroutine. However, in certain cases, it is necessary to control
358when coroutine is prepared for resumption and when it is suspended.
359
360In the following example, a coroutine represents some activity that is driven
361by completions of asynchronous operations `async_op1` and `async_op2` which get
362a coroutine handle as a parameter and resume the coroutine once async
363operation is finished.
364
365.. code-block:: llvm
366
367 void g() {
368 for (;;)
369 if (cond()) {
370 async_op1(<coroutine-handle>); // will resume once async_op1 completes
371 <suspend>
372 do_one();
373 }
374 else {
375 async_op2(<coroutine-handle>); // will resume once async_op2 completes
376 <suspend>
377 do_two();
378 }
379 }
380 }
381
382In this case, coroutine should be ready for resumption prior to a call to
383`async_op1` and `async_op2`. The `coro.save`_ intrinsic is used to indicate a
384point when coroutine should be ready for resumption (namely, when a resume index
385should be stored in the coroutine frame, so that it can be resumed at the
386correct resume point):
387
388.. code-block:: llvm
389
390 if.true:
391 %save1 = call token @llvm.coro.save(i8* %hdl)
392 call void async_op1(i8* %hdl)
393 %suspend1 = call i1 @llvm.coro.suspend(token %save1, i1 false)
394 switch i8 %suspend1, label %suspend [i8 0, label %resume1
395 i8 1, label %cleanup]
396 if.false:
397 %save2 = call token @llvm.coro.save(i8* %hdl)
398 call void async_op2(i8* %hdl)
399 %suspend2 = call i1 @llvm.coro.suspend(token %save2, i1 false)
400 switch i8 %suspend1, label %suspend [i8 0, label %resume2
401 i8 1, label %cleanup]
402
403.. _coroutine promise:
404
405Coroutine Promise
406-----------------
407
408A coroutine author or a frontend may designate a distinguished `alloca` that can
409be used to communicate with the coroutine. This distinguished alloca is called
410**coroutine promise** and is provided as a third parameter to the `coro.begin`_
411intrinsic.
412
413The following coroutine designates a 32 bit integer `promise` and uses it to
414store the current value produced by a coroutine.
415
416.. code-block:: llvm
417
418 define i8* @f(i32 %n) {
419 entry:
420 %promise = alloca i32
421 %pv = bitcast i32* %promise to i8*
422 %size = call i32 @llvm.coro.size.i32()
423 %alloc = call i8* @malloc(i32 %size)
424 %hdl = call noalias i8* @llvm.coro.begin(i8* %alloc, i32 0, i8* %pv, i8* null)
425 br label %loop
426 loop:
427 %n.val = phi i32 [ %n, %entry ], [ %inc, %loop ]
428 %inc = add nsw i32 %n.val, 1
429 store i32 %n.val, i32* %promise
430 %0 = call i8 @llvm.coro.suspend(token none, i1 false)
431 switch i8 %0, label %suspend [i8 0, label %loop
432 i8 1, label %cleanup]
433 cleanup:
434 %mem = call i8* @llvm.coro.free(i8* %hdl)
435 call void @free(i8* %mem)
436 br label %suspend
437 suspend:
438 call void @llvm.coro.end(i8* %hdl, i1 false)
439 ret i8* %hdl
440 }
441
442A coroutine consumer can rely on the `coro.promise`_ intrinsic to access the
443coroutine promise.
444
445.. code-block:: llvm
446
447 define i32 @main() {
448 entry:
449 %hdl = call i8* @f(i32 4)
450 %promise.addr.raw = call i8* @llvm.coro.promise(i8* %hdl, i32 4, i1 false)
451 %promise.addr = bitcast i8* %promise.addr.raw to i32*
452 %val0 = load i32, i32* %promise.addr
453 call void @print(i32 %val0)
454 call void @llvm.coro.resume(i8* %hdl)
455 %val1 = load i32, i32* %promise.addr
456 call void @print(i32 %val1)
457 call void @llvm.coro.resume(i8* %hdl)
458 %val2 = load i32, i32* %promise.addr
459 call void @print(i32 %val2)
460 call void @llvm.coro.destroy(i8* %hdl)
461 ret i32 0
462 }
463
464After example in this section is compiled, result of the compilation will
465exactly like the result of the very first example:
466
467.. code-block:: llvm
468
469 define i32 @main() {
470 entry:
471 tail call void @print(i32 4)
472 tail call void @print(i32 5)
473 tail call void @print(i32 6)
474 ret i32 0
475 }
476
477.. _final:
478.. _final suspend:
479
480Final Suspend
481-------------
482
483A coroutine author or a frontend may designate a particular suspend to be final,
484by setting the second argument of the `coro.suspend`_ intrinsic to `true`.
485Such a suspend point has two properties:
486
487* it is possible to check whether a suspended coroutine is at the final suspend
488 point via `coro.done`_ intrinsic;
489
490* a resumption of a coroutine stopped at the final suspend point leads to
491 undefined behavior. The only possible action for a coroutine at a final
492 suspend point is destroying it via `coro.destroy`_ intrinsic.
493
494From the user perspective, the final suspend point represents an idea of a
495coroutine reaching the end. From the compiler perspective, it is an optimization
496opportunity for reducing number of resume points (and therefore switch cases) in
497the resume function.
498
499The following is an example of a function that keeps resuming the coroutine
500until the final suspend point is reached after which point the coroutine is
501destroyed:
502
503.. code-block:: llvm
504
505 define i32 @main() {
506 entry:
507 %hdl = call i8* @f(i32 4)
508 br label %while
509 while:
510 call void @llvm.coro.resume(i8* %hdl)
511 %done = call i1 @llvm.coro.done(i8* %hdl)
512 br i1 %done, label %end, label %while
513 end:
514 call void @llvm.coro.destroy(i8* %hdl)
515 ret i32 0
516 }
517
518Usually, final suspend point is a frontend injected suspend point that does not
519correspond to any explicitly authored suspend point of the high level language.
520For example, for a Python generator that has only one suspend point:
521
522.. code-block:: python
523
524 def coroutine(n):
525 for i in range(n):
526 yield i
527
528Python frontend would inject two more suspend points, so that the actual code
529looks like this:
530
531.. code-block:: C
532
533 void* coroutine(int n) {
534 int current_value;
535 <designate current_value to be coroutine promise>
536 <SUSPEND> // injected suspend point, so that the coroutine starts suspended
537 for (int i = 0; i < n; ++i) {
538 current_value = i; <SUSPEND>; // corresponds to "yield i"
539 }
540 <SUSPEND final=true> // injected final suspend point
541 }
542
543and python iterator `__next__` would look like:
544
545.. code-block:: C++
546
547 int __next__(void* hdl) {
548 coro.resume(hdl);
549 if (coro.done(hdl)) throw StopIteration();
550 return *(int*)coro.promise(hdl, 4, false);
551 }
552
553Intrinsics
554==========
555
556Coroutine Manipulation Intrinsics
557---------------------------------
558
559Intrinsics described in this section are used to manipulate an existing
560coroutine. They can be used in any function which happen to have a pointer
561to a `coroutine frame`_ or a pointer to a `coroutine promise`_.
562
563.. _coro.destroy:
564
565'llvm.coro.destroy' Intrinsic
566^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
567
568Syntax:
569"""""""
570
571::
572
573 declare void @llvm.coro.destroy(i8* <handle>)
574
575Overview:
576"""""""""
577
578The '``llvm.coro.destroy``' intrinsic destroys a suspended
579coroutine.
580
581Arguments:
582""""""""""
583
584The argument is a coroutine handle to a suspended coroutine.
585
586Semantics:
587""""""""""
588
589When possible, the `coro.destroy` intrinsic is replaced with a direct call to
590the coroutine destroy function. Otherwise it is replaced with an indirect call
591based on the function pointer for the destroy function stored in the coroutine
592frame. Destroying a coroutine that is not suspended leads to undefined behavior.
593
594.. _coro.resume:
595
596'llvm.coro.resume' Intrinsic
597^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
598
599::
600
601 declare void @llvm.coro.resume(i8* <handle>)
602
603Overview:
604"""""""""
605
606The '``llvm.coro.resume``' intrinsic resumes a suspended coroutine.
607
608Arguments:
609""""""""""
610
611The argument is a handle to a suspended coroutine.
612
613Semantics:
614""""""""""
615
616When possible, the `coro.resume` intrinsic is replaced with a direct call to the
617coroutine resume function. Otherwise it is replaced with an indirect call based
618on the function pointer for the resume function stored in the coroutine frame.
619Resuming a coroutine that is not suspended leads to undefined behavior.
620
621.. _coro.done:
622
623'llvm.coro.done' Intrinsic
624^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
625
626::
627
628 declare i1 @llvm.coro.done(i8* <handle>)
629
630Overview:
631"""""""""
632
633The '``llvm.coro.done``' intrinsic checks whether a suspended coroutine is at
634the final suspend point or not.
635
636Arguments:
637""""""""""
638
639The argument is a handle to a suspended coroutine.
640
641Semantics:
642""""""""""
643
644Using this intrinsic on a coroutine that does not have a `final suspend`_ point
645or on a coroutine that is not suspended leads to undefined behavior.
646
647.. _coro.promise:
648
649'llvm.coro.promise' Intrinsic
650^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
651
652::
653
654 declare i8* @llvm.coro.promise(i8* <ptr>, i32 <alignment>, i1 <from>)
655
656Overview:
657"""""""""
658
659The '``llvm.coro.promise``' intrinsic obtains a pointer to a
660`coroutine promise`_ given a coroutine handle and vice versa.
661
662Arguments:
663""""""""""
664
665The first argument is a handle to a coroutine if `from` is false. Otherwise,
666it is a pointer to a coroutine promise.
667
668The second argument is an alignment requirements of the promise.
669If a frontend designated `%promise = alloca i32` as a promise, the alignment
670argument to `coro.promise` should be the alignment of `i32` on the target
671platform. If a frontend designated `%promise = alloca i32, align 16` as a
672promise, the alignment argument should be 16.
673This argument only accepts constants.
674
675The third argument is a boolean indicating a direction of the transformation.
676If `from` is true, the intrinsic returns a coroutine handle given a pointer
677to a promise. If `from` is false, the intrinsics return a pointer to a promise
678from a coroutine handle. This argument only accepts constants.
679
680Semantics:
681""""""""""
682
683Using this intrinsic on a coroutine that does not have a coroutine promise
684leads to undefined behavior. It is possible to read and modify coroutine
685promise of the coroutine which is currently executing. The coroutine author and
686a coroutine user are responsible to makes sure there is no data races.
687
688Example:
689""""""""
690
691.. code-block:: llvm
692
693 define i8* @f(i32 %n) {
694 entry:
695 %promise = alloca i32
696 %pv = bitcast i32* %promise to i8*
697 ...
698 ; the third argument to coro.begin points to the coroutine promise.
699 %hdl = call noalias i8* @llvm.coro.begin(i8* %alloc, i32 0, i8* %pv, i8* null)
700 ...
701 store i32 42, i32* %promise ; store something into the promise
702 ...
703 ret i8* %hdl
704 }
705
706 define i32 @main() {
707 entry:
708 %hdl = call i8* @f(i32 4) ; starts the coroutine and returns its handle
709 %promise.addr.raw = call i8* @llvm.coro.promise(i8* %hdl, i32 4, i1 false)
710 %promise.addr = bitcast i8* %promise.addr.raw to i32*
711 %val = load i32, i32* %promise.addr ; load a value from the promise
712 call void @print(i32 %val)
713 call void @llvm.coro.destroy(i8* %hdl)
714 ret i32 0
715 }
716
717.. _coroutine intrinsics:
718
719Coroutine Structure Intrinsics
720------------------------------
721Intrinsics described in this section are used within a coroutine to describe
722the coroutine structure. They should not be used outside of a coroutine.
723
724.. _coro.size:
725
726'llvm.coro.size' Intrinsic
727^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
728::
729
730 declare i32 @llvm.coro.size.i32()
731 declare i64 @llvm.coro.size.i64()
732
733Overview:
734"""""""""
735
736The '``llvm.coro.size``' intrinsic returns the number of bytes
737required to store a `coroutine frame`_.
738
739Arguments:
740""""""""""
741
742None
743
744Semantics:
745""""""""""
746
747The `coro.size` intrinsic is lowered to a constant representing the size of
748the coroutine frame.
749
750.. _coro.begin:
751
752'llvm.coro.begin' Intrinsic
753^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
754::
755
756 declare i8* @llvm.coro.begin(i8* <mem>, i32 <align>, i8* <promise>, i8* <fnaddr>)
757
758Overview:
759"""""""""
760
761The '``llvm.coro.begin``' intrinsic returns an address of the
762coroutine frame.
763
764Arguments:
765""""""""""
766
767The first argument is a pointer to a block of memory in which coroutine frame
768may use if memory for the coroutine frame needs to be allocated dynamically.
769
770The second argument provides information on the alignment of the memory returned
771by the allocation function and given to `coro.begin` by the first argument. If
772this argument is 0, the memory is assumed to be aligned to 2 * sizeof(i8*).
773This argument only accepts constants.
774
775The third argument, if not `null`, designates a particular alloca instruction to
776be a `coroutine promise`_.
777
778The fourth argument is `null` before coroutine is split, and later is replaced
779to point to a private global constant array containing function pointers to
780outlined resume and destroy parts of the coroutine.
781
782Semantics:
783""""""""""
784
785Depending on the alignment requirements of the objects in the coroutine frame
786and/or on the codegen compactness reasons the pointer returned from `coro.begin`
787may be at offset to the `%mem` argument. (This could be beneficial if
788instructions that express relative access to data can be more compactly encoded
789with small positive and negative offsets).
790
791Frontend should emit exactly one `coro.begin` intrinsic per coroutine.
792
793.. _coro.free:
794
795'llvm.coro.free' Intrinsic
796^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
797::
798
799 declare i8* @llvm.coro.free(i8* <frame>)
800
801Overview:
802"""""""""
803
804The '``llvm.coro.free``' intrinsic returns a pointer to a block of memory where
805coroutine frame is stored or `null` if this instance of a coroutine did not use
806dynamically allocated memory for its coroutine frame.
807
808Arguments:
809""""""""""
810
811A pointer to the coroutine frame. This should be the same pointer that was
812returned by prior `coro.begin` call.
813
814Example (custom deallocation function):
815"""""""""""""""""""""""""""""""""""""""
816
817.. code-block:: llvm
818
819 cleanup:
820 %mem = call i8* @llvm.coro.free(i8* %frame)
821 %mem_not_null = icmp ne i8* %mem, null
822 br i1 %mem_not_null, label %if.then, label %if.end
823 if.then:
824 call void @CustomFree(i8* %mem)
825 br label %if.end
826 if.end:
827 ret void
828
829Example (standard deallocation functions):
830""""""""""""""""""""""""""""""""""""""""""
831
832.. code-block:: llvm
833
834 cleanup:
835 %mem = call i8* @llvm.coro.free(i8* %frame)
836 call void @free(i8* %mem)
837 ret void
838
839.. _coro.alloc:
840
841'llvm.coro.alloc' Intrinsic
842^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
843::
844
845 declare i8* @llvm.coro.alloc()
846
847Overview:
848"""""""""
849
850The '``llvm.coro.alloc``' intrinsic returns an address of the memory on the
851callers frame where coroutine frame of this coroutine can be placed or `null`
852otherwise.
853
854Arguments:
855""""""""""
856
857None
858
859Semantics:
860""""""""""
861
862If the coroutine is eligible for heap elision, this intrinsic is lowered to an
863alloca storing the coroutine frame. Otherwise, it is lowered to constant `null`.
864This intrinsic only needs to be used if a custom allocation function is used
865(i.e. a function not recognized by LLVM as a memory allocation function) and the
866language rules allow for custom allocation / deallocation to be elided when not
867needed.
868
869Example:
870""""""""
871
872.. code-block:: llvm
873
874 entry:
875 %elide = call i8* @llvm.coro.alloc()
876 %0 = icmp ne i8* %elide, null
877 br i1 %0, label %coro.begin, label %coro.alloc
878
879 coro.alloc:
880 %frame.size = call i32 @llvm.coro.size()
881 %alloc = call i8* @MyAlloc(i32 %frame.size)
882 br label %coro.begin
883
884 coro.begin:
885 %phi = phi i8* [ %elide, %entry ], [ %alloc, %coro.alloc ]
886 %frame = call i8* @llvm.coro.begin(i8* %phi, i32 0, i8* null, i8* null)
887
888.. _coro.frame:
889
890'llvm.coro.frame' Intrinsic
891^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
892::
893
894 declare i8* @llvm.coro.frame()
895
896Overview:
897"""""""""
898
899The '``llvm.coro.frame``' intrinsic returns an address of the coroutine frame of
900the enclosing coroutine.
901
902Arguments:
903""""""""""
904
905None
906
907Semantics:
908""""""""""
909
910This intrinsic is lowered to refer to the `coro.begin`_ instruction. This is
911a frontend convenience intrinsic that makes it easier to refer to the
912coroutine frame.
913
914.. _coro.end:
915
916'llvm.coro.end' Intrinsic
917^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
918::
919
920 declare void @llvm.coro.end(i8* <handle>, i1 <unwind>)
921
922Overview:
923"""""""""
924
925The '``llvm.coro.end``' marks the point where execution of the resume part of
926the coroutine should end and control returns back to the caller.
927
928
929Arguments:
930""""""""""
931
932The first argument should refer to the coroutine handle of the enclosing coroutine.
933
934The second argument should be `true` if this coro.end is in the block that is
935part of the unwind sequence leaving the coroutine body due to exception prior to
936the first reaching any suspend points, and `false` otherwise.
937
938Semantics:
939""""""""""
940The `coro.end`_ intrinsic is a no-op during an initial invocation of the
941coroutine. When the coroutine resumes, the intrinsic marks the point when
942coroutine need to return control back to the caller.
943
944This intrinsic is removed by the CoroSplit pass when a coroutine is split into
945the start, resume and destroy parts. In start part, the intrinsic is removed,
946in resume and destroy parts, it is replaced with `ret void` instructions and
947the rest of the block containing `coro.end` instruction is discarded.
948
949In landing pads it is replaced with an appropriate instruction to unwind to
950caller.
951
952A frontend is allowed to supply null as the first parameter, in this case
953`coro-early` pass will replace the null with an appropriate coroutine handle
954value.
955
956.. _coro.suspend:
957.. _suspend points:
958
959'llvm.coro.suspend' Intrinsic
960^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
961::
962
963 declare i8 @llvm.coro.suspend(token <save>, i1 <final>)
964
965Overview:
966"""""""""
967
968The '``llvm.coro.suspend``' marks the point where execution of the coroutine
969need to get suspended and control returned back to the caller.
970Conditional branches consuming the result of this intrinsic lead to basic blocks
971where coroutine should proceed when suspended (-1), resumed (0) or destroyed
972(1).
973
974Arguments:
975""""""""""
976
977The first argument refers to a token of `coro.save` intrinsic that marks the
978point when coroutine state is prepared for suspension. If `none` token is passed,
979the intrinsic behaves as if there were a `coro.save` immediately preceding
980the `coro.suspend` intrinsic.
981
982The second argument indicates whether this suspension point is `final`_.
983The second argument only accepts constants. If more than one suspend point is
984designated as final, the resume and destroy branches should lead to the same
985basic blocks.
986
987Example (normal suspend point):
988"""""""""""""""""""""""""""""""
989
990.. code-block:: llvm
991
992 %0 = call i8 @llvm.coro.suspend(token none, i1 false)
993 switch i8 %0, label %suspend [i8 0, label %resume
994 i8 1, label %cleanup]
995
996Example (final suspend point):
997""""""""""""""""""""""""""""""
998
999.. code-block:: llvm
1000
1001 while.end:
1002 %s.final = call i8 @llvm.coro.suspend(token none, i1 true)
1003 switch i8 %s.final, label %suspend [i8 0, label %trap
1004 i8 1, label %cleanup]
1005 trap:
1006 call void @llvm.trap()
1007 unreachable
1008
1009Semantics:
1010""""""""""
1011
1012If a coroutine that was suspended at the suspend point marked by this intrinsic
1013is resumed via `coro.resume`_ the control will transfer to the basic block
1014of the 0-case. If it is resumed via `coro.destroy`_, it will proceed to the
1015basic block indicated by the 1-case. To suspend, coroutine proceed to the
1016default label.
1017
1018If suspend intrinsic is marked as final, it can consider the `true` branch
1019unreachable and can perform optimizations that can take advantage of that fact.
1020
1021.. _coro.save:
1022
1023'llvm.coro.save' Intrinsic
1024^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1025::
1026
1027 declare token @llvm.coro.save(i8* <handle>)
1028
1029Overview:
1030"""""""""
1031
1032The '``llvm.coro.save``' marks the point where a coroutine need to update its
1033state to prepare for resumption to be considered suspended (and thus eligible
1034for resumption).
1035
1036Arguments:
1037""""""""""
1038
1039The first argument points to a coroutine handle of the enclosing coroutine.
1040
1041Semantics:
1042""""""""""
1043
1044Whatever coroutine state changes are required to enable resumption of
1045the coroutine from the corresponding suspend point should be done at the point
1046of `coro.save` intrinsic.
1047
1048Example:
1049""""""""
1050
1051Separate save and suspend points are necessary when a coroutine is used to
1052represent an asynchronous control flow driven by callbacks representing
1053completions of asynchronous operations.
1054
1055In such a case, a coroutine should be ready for resumption prior to a call to
1056`async_op` function that may trigger resumption of a coroutine from the same or
1057a different thread possibly prior to `async_op` call returning control back
1058to the coroutine:
1059
1060.. code-block:: llvm
1061
1062 %save1 = call token @llvm.coro.save(i8* %hdl)
1063 call void async_op1(i8* %hdl)
1064 %suspend1 = call i1 @llvm.coro.suspend(token %save1, i1 false)
1065 switch i8 %suspend1, label %suspend [i8 0, label %resume1
1066 i8 1, label %cleanup]
1067
1068.. _coro.param:
1069
1070'llvm.coro.param' Intrinsic
1071^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1072::
1073
1074 declare i1 @llvm.coro.param(i8* <original>, i8* <copy>)
1075
1076Overview:
1077"""""""""
1078
1079The '``llvm.coro.param``' is used by the frontend to mark up the code used to
1080construct and destruct copies of the parameters. If the optimizer discovers that
1081a particular parameter copy is not used after any suspends, it can remove the
1082construction and destruction of the copy by replacing corresponding coro.param
1083with `i1 false` and replacing any use of the `copy` with the `original`.
1084
1085Arguments:
1086""""""""""
1087
1088The first argument points to an `alloca` storing the value of a parameter to a
1089coroutine.
1090
1091The second argument points to an `alloca` storing the value of the copy of that
1092parameter.
1093
1094Semantics:
1095""""""""""
1096
1097The optimizer is free to always replace this intrinsic with `i1 true`.
1098
1099The optimizer is also allowed to replace it with `i1 false` provided that the
1100parameter copy is only used prior to control flow reaching any of the suspend
1101points. The code that would be DCE'd if the `coro.param` is replaced with
1102`i1 false` is not considered to be a use of the parameter copy.
1103
1104The frontend can emit this intrinsic if its language rules allow for this
1105optimization.
1106
1107Example:
1108""""""""
1109Consider the following example. A coroutine takes two parameters `a` and `b`
1110that has a destructor and a move constructor.
1111
1112.. code-block:: C++
1113
1114 struct A { ~A(); A(A&&); bool foo(); void bar(); };
1115
1116 task<int> f(A a, A b) {
1117 if (a.foo())
1118 return 42;
1119
1120 a.bar();
1121 co_await read_async(); // introduces suspend point
1122 b.bar();
1123 }
1124
1125Note that, uses of `b` is used after a suspend point and thus must be copied
1126into a coroutine frame, whereas `a` does not have to, since it never used
1127after suspend.
1128
1129A frontend can create parameter copies for `a` and `b` as follows:
1130
1131.. code-block:: C++
1132
1133 task<int> f(A a', A b') {
1134 a = alloca A;
1135 b = alloca A;
1136 // move parameters to its copies
1137 if (coro.param(a', a)) A::A(a, A&& a');
1138 if (coro.param(b', b)) A::A(b, A&& b');
1139 ...
1140 // destroy parameters copies
1141 if (coro.param(a', a)) A::~A(a);
1142 if (coro.param(b', b)) A::~A(b);
1143 }
1144
1145The optimizer can replace coro.param(a',a) with `i1 false` and replace all uses
1146of `a` with `a'`, since it is not used after suspend.
1147
1148The optimizer must replace coro.param(b', b) with `i1 true`, since `b` is used
1149after suspend and therefore, it has to reside in the coroutine frame.
1150
1151Coroutine Transformation Passes
1152===============================
1153CoroEarly
1154---------
1155The pass CoroEarly lowers coroutine intrinsics that hide the details of the
1156structure of the coroutine frame, but, otherwise not needed to be preserved to
1157help later coroutine passes. This pass lowers `coro.frame`_, `coro.done`_,
1158and `coro.promise`_ intrinsics.
1159
1160.. _CoroSplit:
1161
1162CoroSplit
1163---------
1164The pass CoroSplit buides coroutine frame and outlines resume and destroy parts
1165into separate functions.
1166
1167CoroElide
1168---------
1169The pass CoroElide examines if the inlined coroutine is eligible for heap
1170allocation elision optimization. If so, it replaces `coro.alloc` and
1171`coro.begin` intrinsic with an address of a coroutine frame placed on its caller
1172and replaces `coro.free` intrinsics with `null` to remove the deallocation code.
1173This pass also replaces `coro.resume` and `coro.destroy` intrinsics with direct
1174calls to resume and destroy functions for a particular coroutine where possible.
1175
1176CoroCleanup
1177-----------
1178This pass runs late to lower all coroutine related intrinsics not replaced by
1179earlier passes.
1180
1181Upstreaming sequence (rough plan)
1182=================================
1183#. Add documentation. <= we are here
1184#. Add coroutine intrinsics.
1185#. Add empty coroutine passes.
1186#. Add coroutine devirtualization + tests.
1187#. Add CGSCC restart trigger + tests.
1188#. Add coroutine heap elision + tests.
1189#. Add custom allocation heap elision + tests.
1190#. Add coroutine splitting logic + tests.
1191#. Add simple coroutine frame builder + tests.
1192#. Add the rest of the logic + tests. (Maybe split further as needed).
1193
1194Areas Requiring Attention
1195=========================
1196#. A coroutine frame is bigger than it could be. Adding stack packing and stack
1197 coloring like optimization on the coroutine frame will result in tighter
1198 coroutine frames.
1199
1200#. Take advantage of the lifetime intrinsics for the data that goes into the
1201 coroutine frame. Leave lifetime intrinsics as is for the data that stays in
1202 allocas.
1203
1204#. The CoroElide optimization pass relies on coroutine ramp function to be
1205 inlined. It would be beneficial to split the ramp function further to
1206 increase the chance that it will get inlined into its caller.
1207
1208#. Design a convention that would make it possible to apply coroutine heap
1209 elision optimization across ABI boundaries.
1210
1211#. Cannot handle coroutines with `inalloca` parameters (used in x86 on Windows).
1212
1213#. Alignment is ignored by coro.begin and coro.free intrinsics.
1214
1215#. Make required changes to make sure that coroutine optimizations work with
1216 LTO.
1217
1218#. More tests, more tests, more tests