1 =====================================
3 =====================================
10 This is a work in progress. Compatibility across LLVM releases is not
18 LLVM coroutines are functions that have one or more `suspend points`_.
19 When a suspend point is reached, the execution of a coroutine is suspended and
20 control is returned back to its caller. A suspended coroutine can be resumed
21 to continue execution from the last suspend point or it can be destroyed.
23 In the following example, we call function `f` (which may or may not be a
24 coroutine itself) that returns a handle to a suspended coroutine
25 (**coroutine handle**) that is used by `main` to resume the coroutine twice and
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)
41 In addition to the function stack frame which exists when a coroutine is
42 executing, there is an additional region of storage that contains objects that
43 keep the coroutine state when a coroutine is suspended. This region of storage
44 is called the **coroutine frame**. It is created when a coroutine is called
45 and destroyed when a coroutine either runs to completion or is destroyed
48 LLVM currently supports two styles of coroutine lowering. These styles
49 support substantially different sets of features, have substantially
50 different ABIs, and expect substantially different patterns of frontend
51 code generation. However, the styles also have a great deal in common.
53 In all cases, an LLVM coroutine is initially represented as an ordinary LLVM
54 function that has calls to `coroutine intrinsics`_ defining the structure of
55 the coroutine. The coroutine function is then, in the most general case,
56 rewritten by the coroutine lowering passes to become the "ramp function",
57 the initial entrypoint of the coroutine, which executes until a suspend point
58 is first reached. The remainder of the original coroutine function is split
59 out into some number of "resume functions". Any state which must persist
60 across suspensions is stored in the coroutine frame. The resume functions
61 must somehow be able to handle either a "normal" resumption, which continues
62 the normal execution of the coroutine, or an "abnormal" resumption, which
63 must unwind the coroutine without attempting to suspend it.
65 Switched-Resume Lowering
66 ------------------------
68 In LLVM's standard switched-resume lowering, signaled by the use of
69 `llvm.coro.id`, the coroutine frame is stored as part of a "coroutine
70 object" which represents a handle to a particular invocation of the
71 coroutine. All coroutine objects support a common ABI allowing certain
72 features to be used without knowing anything about the coroutine's
75 - A coroutine object can be queried to see if it has reached completion
76 with `llvm.coro.done`.
78 - A coroutine object can be resumed normally if it has not already reached
79 completion with `llvm.coro.resume`.
81 - A coroutine object can be destroyed, invalidating the coroutine object,
82 with `llvm.coro.destroy`. This must be done separately even if the
83 coroutine has reached completion normally.
85 - "Promise" storage, which is known to have a certain size and alignment,
86 can be projected out of the coroutine object with `llvm.coro.promise`.
87 The coroutine implementation must have been compiled to define a promise
88 of the same size and alignment.
90 In general, interacting with a coroutine object in any of these ways while
91 it is running has undefined behavior.
93 The coroutine function is split into three functions, representing three
94 different ways that control can enter the coroutine:
96 1. the ramp function that is initially invoked, which takes arbitrary
97 arguments and returns a pointer to the coroutine object;
99 2. a coroutine resume function that is invoked when the coroutine is resumed,
100 which takes a pointer to the coroutine object and returns `void`;
102 3. a coroutine destroy function that is invoked when the coroutine is
103 destroyed, which takes a pointer to the coroutine object and returns
106 Because the resume and destroy functions are shared across all suspend
107 points, suspend points must store the index of the active suspend in
108 the coroutine object, and the resume/destroy functions must switch over
109 that index to get back to the correct point. Hence the name of this
112 Pointers to the resume and destroy functions are stored in the coroutine
113 object at known offsets which are fixed for all coroutines. A completed
114 coroutine is represented with a null resume function.
116 There is a somewhat complex protocol of intrinsics for allocating and
117 deallocating the coroutine object. It is complex in order to allow the
118 allocation to be elided due to inlining. This protocol is discussed
119 in further detail below.
121 The frontend may generate code to call the coroutine function directly;
122 this will become a call to the ramp function and will return a pointer
123 to the coroutine object. The frontend should always resume or destroy
124 the coroutine using the corresping intrinsics.
126 Returned-Continuation Lowering
127 ------------------------------
129 In returned-continuation lowering, signaled by the use of
130 `llvm.coro.id.retcon` or `llvm.coro.id.retcon.once`, some aspects of
131 the ABI must be handled more explicitly by the frontend.
133 In this lowering, every suspend point takes a list of "yielded values"
134 which are returned back to the caller along with a function pointer,
135 called the continuation function. The coroutine is resumed by simply
136 calling this continuation function pointer. The original coroutine
137 is divided into the ramp function and then an arbitrary number of
138 these continuation functions, one for each suspend point.
140 LLVM actually supports two closely-related returned-continuation
143 - In normal returned-continuation lowering, the coroutine may suspend
144 itself multiple times. This means that a continuation function
145 itself returns another continuation pointer, as well as a list of
148 The coroutine indicates that it has run to completion by returning
149 a null continuation pointer. Any yielded values will be `undef`
152 - In yield-once returned-continuation lowering, the coroutine must
153 suspend itself exactly once (or throw an exception). The ramp
154 function returns a continuation function pointer and yielded
155 values, but the continuation function simply returns `void`
156 when the coroutine has run to completion.
158 The coroutine frame is maintained in a fixed-size buffer that is
159 passed to the `coro.id` intrinsic, which guarantees a certain size
160 and alignment statically. The same buffer must be passed to the
161 continuation function(s). The coroutine will allocate memory if the
162 buffer is insufficient, in which case it will need to store at
163 least that pointer in the buffer; therefore the buffer must always
164 be at least pointer-sized. How the coroutine uses the buffer may
165 vary between suspend points.
167 In addition to the buffer pointer, continuation functions take an
168 argument indicating whether the coroutine is being resumed normally
169 (zero) or abnormally (non-zero).
171 LLVM is currently ineffective at statically eliminating allocations
172 after fully inlining returned-continuation coroutines into a caller.
173 This may be acceptable if LLVM's coroutine support is primarily being
174 used for low-level lowering and inlining is expected to be applied
175 earlier in the pipeline.
177 Coroutines by Example
178 =====================
180 The examples below are all of switched-resume coroutines.
182 Coroutine Representation
183 ------------------------
185 Let's look at an example of an LLVM coroutine with the behavior sketched
186 by the following pseudo-code.
193 <suspend> // returns a coroutine handle on first suspend
197 This coroutine calls some function `print` with value `n` as an argument and
198 suspends 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
199 a `main` shown in the previous section. It will call `print` with values 4, 5
200 and 6 after which the coroutine will be destroyed.
202 The LLVM IR for this coroutine looks like this:
206 define i8* @f(i32 %n) {
208 %id = call token @llvm.coro.id(i32 0, i8* null, i8* null, i8* null)
209 %size = call i32 @llvm.coro.size.i32()
210 %alloc = call i8* @malloc(i32 %size)
211 %hdl = call noalias i8* @llvm.coro.begin(token %id, i8* %alloc)
214 %n.val = phi i32 [ %n, %entry ], [ %inc, %loop ]
215 %inc = add nsw i32 %n.val, 1
216 call void @print(i32 %n.val)
217 %0 = call i8 @llvm.coro.suspend(token none, i1 false)
218 switch i8 %0, label %suspend [i8 0, label %loop
219 i8 1, label %cleanup]
221 %mem = call i8* @llvm.coro.free(token %id, i8* %hdl)
222 call void @free(i8* %mem)
225 %unused = call i1 @llvm.coro.end(i8* %hdl, i1 false)
229 The `entry` block establishes the coroutine frame. The `coro.size`_ intrinsic is
230 lowered to a constant representing the size required for the coroutine frame.
231 The `coro.begin`_ intrinsic initializes the coroutine frame and returns the
232 coroutine handle. The second parameter of `coro.begin` is given a block of memory
233 to be used if the coroutine frame needs to be allocated dynamically.
234 The `coro.id`_ intrinsic serves as coroutine identity useful in cases when the
235 `coro.begin`_ intrinsic get duplicated by optimization passes such as
238 The `cleanup` block destroys the coroutine frame. The `coro.free`_ intrinsic,
239 given the coroutine handle, returns a pointer of the memory block to be freed or
240 `null` if the coroutine frame was not allocated dynamically. The `cleanup`
241 block is entered when coroutine runs to completion by itself or destroyed via
242 call to the `coro.destroy`_ intrinsic.
244 The `suspend` block contains code to be executed when coroutine runs to
245 completion or suspended. The `coro.end`_ intrinsic marks the point where
246 a coroutine needs to return control back to the caller if it is not an initial
247 invocation of the coroutine.
249 The `loop` blocks represents the body of the coroutine. The `coro.suspend`_
250 intrinsic in combination with the following switch indicates what happens to
251 control flow when a coroutine is suspended (default case), resumed (case 0) or
254 Coroutine Transformation
255 ------------------------
257 One of the steps of coroutine lowering is building the coroutine frame. The
258 def-use chains are analyzed to determine which objects need be kept alive across
259 suspend points. In the coroutine shown in the previous section, use of virtual register
260 `%n.val` is separated from the definition by a suspend point, therefore, it
261 cannot reside on the stack frame since the latter goes away once the coroutine
262 is suspended and control is returned back to the caller. An i32 slot is
263 allocated in the coroutine frame and `%n.val` is spilled and reloaded from that
266 We also store addresses of the resume and destroy functions so that the
267 `coro.resume` and `coro.destroy` intrinsics can resume and destroy the coroutine
268 when its identity cannot be determined statically at compile time. For our
269 example, the coroutine frame will be:
273 %f.frame = type { void (%f.frame*)*, void (%f.frame*)*, i32 }
275 After resume and destroy parts are outlined, function `f` will contain only the
276 code responsible for creation and initialization of the coroutine frame and
277 execution of the coroutine until a suspend point is reached:
281 define i8* @f(i32 %n) {
283 %id = call token @llvm.coro.id(i32 0, i8* null, i8* null, i8* null)
284 %alloc = call noalias i8* @malloc(i32 24)
285 %0 = call noalias i8* @llvm.coro.begin(token %id, i8* %alloc)
286 %frame = bitcast i8* %0 to %f.frame*
287 %1 = getelementptr %f.frame, %f.frame* %frame, i32 0, i32 0
288 store void (%f.frame*)* @f.resume, void (%f.frame*)** %1
289 %2 = getelementptr %f.frame, %f.frame* %frame, i32 0, i32 1
290 store void (%f.frame*)* @f.destroy, void (%f.frame*)** %2
292 %inc = add nsw i32 %n, 1
293 %inc.spill.addr = getelementptr inbounds %f.Frame, %f.Frame* %FramePtr, i32 0, i32 2
294 store i32 %inc, i32* %inc.spill.addr
295 call void @print(i32 %n)
300 Outlined resume part of the coroutine will reside in function `f.resume`:
304 define internal fastcc void @f.resume(%f.frame* %frame.ptr.resume) {
306 %inc.spill.addr = getelementptr %f.frame, %f.frame* %frame.ptr.resume, i64 0, i32 2
307 %inc.spill = load i32, i32* %inc.spill.addr, align 4
308 %inc = add i32 %n.val, 1
309 store i32 %inc, i32* %inc.spill.addr, align 4
310 tail call void @print(i32 %inc)
314 Whereas function `f.destroy` will contain the cleanup code for the coroutine:
318 define internal fastcc void @f.destroy(%f.frame* %frame.ptr.destroy) {
320 %0 = bitcast %f.frame* %frame.ptr.destroy to i8*
321 tail call void @free(i8* %0)
325 Avoiding Heap Allocations
326 -------------------------
328 A particular coroutine usage pattern, which is illustrated by the `main`
329 function in the overview section, where a coroutine is created, manipulated and
330 destroyed by the same calling function, is common for coroutines implementing
331 RAII idiom and is suitable for allocation elision optimization which avoid
332 dynamic allocation by storing the coroutine frame as a static `alloca` in its
335 In the entry block, we will call `coro.alloc`_ intrinsic that will return `true`
336 when dynamic allocation is required, and `false` if dynamic allocation is
342 %id = call token @llvm.coro.id(i32 0, i8* null, i8* null, i8* null)
343 %need.dyn.alloc = call i1 @llvm.coro.alloc(token %id)
344 br i1 %need.dyn.alloc, label %dyn.alloc, label %coro.begin
346 %size = call i32 @llvm.coro.size.i32()
347 %alloc = call i8* @CustomAlloc(i32 %size)
350 %phi = phi i8* [ null, %entry ], [ %alloc, %dyn.alloc ]
351 %hdl = call noalias i8* @llvm.coro.begin(token %id, i8* %phi)
353 In the cleanup block, we will make freeing the coroutine frame conditional on
354 `coro.free`_ intrinsic. If allocation is elided, `coro.free`_ returns `null`
355 thus skipping the deallocation code:
360 %mem = call i8* @llvm.coro.free(token %id, i8* %hdl)
361 %need.dyn.free = icmp ne i8* %mem, null
362 br i1 %need.dyn.free, label %dyn.free, label %if.end
364 call void @CustomFree(i8* %mem)
369 With allocations and deallocations represented as described as above, after
370 coroutine heap allocation elision optimization, the resulting main will be:
376 call void @print(i32 4)
377 call void @print(i32 5)
378 call void @print(i32 6)
382 Multiple Suspend Points
383 -----------------------
385 Let's consider the coroutine that has more than one suspend point:
398 Matching LLVM code would look like (with the rest of the code remaining the same
399 as the code in the previous section):
404 %n.addr = phi i32 [ %n, %entry ], [ %inc, %loop.resume ]
405 call void @print(i32 %n.addr) #4
406 %2 = call i8 @llvm.coro.suspend(token none, i1 false)
407 switch i8 %2, label %suspend [i8 0, label %loop.resume
408 i8 1, label %cleanup]
410 %inc = add nsw i32 %n.addr, 1
411 %sub = xor i32 %n.addr, -1
412 call void @print(i32 %sub)
413 %3 = call i8 @llvm.coro.suspend(token none, i1 false)
414 switch i8 %3, label %suspend [i8 0, label %loop
415 i8 1, label %cleanup]
417 In this case, the coroutine frame would include a suspend index that will
418 indicate at which suspend point the coroutine needs to resume. The resume
419 function will use an index to jump to an appropriate basic block and will look
424 define internal fastcc void @f.Resume(%f.Frame* %FramePtr) {
426 %index.addr = getelementptr inbounds %f.Frame, %f.Frame* %FramePtr, i64 0, i32 2
427 %index = load i8, i8* %index.addr, align 1
428 %switch = icmp eq i8 %index, 0
429 %n.addr = getelementptr inbounds %f.Frame, %f.Frame* %FramePtr, i64 0, i32 3
430 %n = load i32, i32* %n.addr, align 4
431 br i1 %switch, label %loop.resume, label %loop
434 %sub = xor i32 %n, -1
435 call void @print(i32 %sub)
438 %inc = add nsw i32 %n, 1
439 store i32 %inc, i32* %n.addr, align 4
440 tail call void @print(i32 %inc)
444 %storemerge = phi i8 [ 0, %loop ], [ 1, %loop.resume ]
445 store i8 %storemerge, i8* %index.addr, align 1
449 If different cleanup code needs to get executed for different suspend points,
450 a similar switch will be in the `f.destroy` function.
454 Using suspend index in a coroutine state and having a switch in `f.resume` and
455 `f.destroy` is one of the possible implementation strategies. We explored
456 another option where a distinct `f.resume1`, `f.resume2`, etc. are created for
457 every suspend point, and instead of storing an index, the resume and destroy
458 function pointers are updated at every suspend. Early testing showed that the
459 current approach is easier on the optimizer than the latter so it is a
460 lowering strategy implemented at the moment.
462 Distinct Save and Suspend
463 -------------------------
465 In the previous example, setting a resume index (or some other state change that
466 needs to happen to prepare a coroutine for resumption) happens at the same time as
467 a suspension of a coroutine. However, in certain cases, it is necessary to control
468 when coroutine is prepared for resumption and when it is suspended.
470 In the following example, a coroutine represents some activity that is driven
471 by completions of asynchronous operations `async_op1` and `async_op2` which get
472 a coroutine handle as a parameter and resume the coroutine once async
473 operation is finished.
480 async_op1(<coroutine-handle>); // will resume once async_op1 completes
485 async_op2(<coroutine-handle>); // will resume once async_op2 completes
492 In this case, coroutine should be ready for resumption prior to a call to
493 `async_op1` and `async_op2`. The `coro.save`_ intrinsic is used to indicate a
494 point when coroutine should be ready for resumption (namely, when a resume index
495 should be stored in the coroutine frame, so that it can be resumed at the
496 correct resume point):
501 %save1 = call token @llvm.coro.save(i8* %hdl)
502 call void @async_op1(i8* %hdl)
503 %suspend1 = call i1 @llvm.coro.suspend(token %save1, i1 false)
504 switch i8 %suspend1, label %suspend [i8 0, label %resume1
505 i8 1, label %cleanup]
507 %save2 = call token @llvm.coro.save(i8* %hdl)
508 call void @async_op2(i8* %hdl)
509 %suspend2 = call i1 @llvm.coro.suspend(token %save2, i1 false)
510 switch i8 %suspend1, label %suspend [i8 0, label %resume2
511 i8 1, label %cleanup]
513 .. _coroutine promise:
518 A coroutine author or a frontend may designate a distinguished `alloca` that can
519 be used to communicate with the coroutine. This distinguished alloca is called
520 **coroutine promise** and is provided as the second parameter to the
521 `coro.id`_ intrinsic.
523 The following coroutine designates a 32 bit integer `promise` and uses it to
524 store the current value produced by a coroutine.
528 define i8* @f(i32 %n) {
530 %promise = alloca i32
531 %pv = bitcast i32* %promise to i8*
532 %id = call token @llvm.coro.id(i32 0, i8* %pv, i8* null, i8* null)
533 %need.dyn.alloc = call i1 @llvm.coro.alloc(token %id)
534 br i1 %need.dyn.alloc, label %dyn.alloc, label %coro.begin
536 %size = call i32 @llvm.coro.size.i32()
537 %alloc = call i8* @malloc(i32 %size)
540 %phi = phi i8* [ null, %entry ], [ %alloc, %dyn.alloc ]
541 %hdl = call noalias i8* @llvm.coro.begin(token %id, i8* %phi)
544 %n.val = phi i32 [ %n, %coro.begin ], [ %inc, %loop ]
545 %inc = add nsw i32 %n.val, 1
546 store i32 %n.val, i32* %promise
547 %0 = call i8 @llvm.coro.suspend(token none, i1 false)
548 switch i8 %0, label %suspend [i8 0, label %loop
549 i8 1, label %cleanup]
551 %mem = call i8* @llvm.coro.free(token %id, i8* %hdl)
552 call void @free(i8* %mem)
555 %unused = call i1 @llvm.coro.end(i8* %hdl, i1 false)
559 A coroutine consumer can rely on the `coro.promise`_ intrinsic to access the
566 %hdl = call i8* @f(i32 4)
567 %promise.addr.raw = call i8* @llvm.coro.promise(i8* %hdl, i32 4, i1 false)
568 %promise.addr = bitcast i8* %promise.addr.raw to i32*
569 %val0 = load i32, i32* %promise.addr
570 call void @print(i32 %val0)
571 call void @llvm.coro.resume(i8* %hdl)
572 %val1 = load i32, i32* %promise.addr
573 call void @print(i32 %val1)
574 call void @llvm.coro.resume(i8* %hdl)
575 %val2 = load i32, i32* %promise.addr
576 call void @print(i32 %val2)
577 call void @llvm.coro.destroy(i8* %hdl)
581 After example in this section is compiled, result of the compilation will be:
587 tail call void @print(i32 4)
588 tail call void @print(i32 5)
589 tail call void @print(i32 6)
599 A coroutine author or a frontend may designate a particular suspend to be final,
600 by setting the second argument of the `coro.suspend`_ intrinsic to `true`.
601 Such a suspend point has two properties:
603 * it is possible to check whether a suspended coroutine is at the final suspend
604 point via `coro.done`_ intrinsic;
606 * a resumption of a coroutine stopped at the final suspend point leads to
607 undefined behavior. The only possible action for a coroutine at a final
608 suspend point is destroying it via `coro.destroy`_ intrinsic.
610 From the user perspective, the final suspend point represents an idea of a
611 coroutine reaching the end. From the compiler perspective, it is an optimization
612 opportunity for reducing number of resume points (and therefore switch cases) in
615 The following is an example of a function that keeps resuming the coroutine
616 until the final suspend point is reached after which point the coroutine is
623 %hdl = call i8* @f(i32 4)
626 call void @llvm.coro.resume(i8* %hdl)
627 %done = call i1 @llvm.coro.done(i8* %hdl)
628 br i1 %done, label %end, label %while
630 call void @llvm.coro.destroy(i8* %hdl)
634 Usually, final suspend point is a frontend injected suspend point that does not
635 correspond to any explicitly authored suspend point of the high level language.
636 For example, for a Python generator that has only one suspend point:
638 .. code-block:: python
644 Python frontend would inject two more suspend points, so that the actual code
649 void* coroutine(int n) {
651 <designate current_value to be coroutine promise>
652 <SUSPEND> // injected suspend point, so that the coroutine starts suspended
653 for (int i = 0; i < n; ++i) {
654 current_value = i; <SUSPEND>; // corresponds to "yield i"
656 <SUSPEND final=true> // injected final suspend point
659 and python iterator `__next__` would look like:
663 int __next__(void* hdl) {
665 if (coro.done(hdl)) throw StopIteration();
666 return *(int*)coro.promise(hdl, 4, false);
673 Coroutine Manipulation Intrinsics
674 ---------------------------------
676 Intrinsics described in this section are used to manipulate an existing
677 coroutine. They can be used in any function which happen to have a pointer
678 to a `coroutine frame`_ or a pointer to a `coroutine promise`_.
682 'llvm.coro.destroy' Intrinsic
683 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
690 declare void @llvm.coro.destroy(i8* <handle>)
695 The '``llvm.coro.destroy``' intrinsic destroys a suspended
696 switched-resume coroutine.
701 The argument is a coroutine handle to a suspended coroutine.
706 When possible, the `coro.destroy` intrinsic is replaced with a direct call to
707 the coroutine destroy function. Otherwise it is replaced with an indirect call
708 based on the function pointer for the destroy function stored in the coroutine
709 frame. Destroying a coroutine that is not suspended leads to undefined behavior.
713 'llvm.coro.resume' Intrinsic
714 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
718 declare void @llvm.coro.resume(i8* <handle>)
723 The '``llvm.coro.resume``' intrinsic resumes a suspended switched-resume coroutine.
728 The argument is a handle to a suspended coroutine.
733 When possible, the `coro.resume` intrinsic is replaced with a direct call to the
734 coroutine resume function. Otherwise it is replaced with an indirect call based
735 on the function pointer for the resume function stored in the coroutine frame.
736 Resuming a coroutine that is not suspended leads to undefined behavior.
740 'llvm.coro.done' Intrinsic
741 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
745 declare i1 @llvm.coro.done(i8* <handle>)
750 The '``llvm.coro.done``' intrinsic checks whether a suspended
751 switched-resume coroutine is at the final suspend point or not.
756 The argument is a handle to a suspended coroutine.
761 Using this intrinsic on a coroutine that does not have a `final suspend`_ point
762 or on a coroutine that is not suspended leads to undefined behavior.
766 'llvm.coro.promise' Intrinsic
767 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
771 declare i8* @llvm.coro.promise(i8* <ptr>, i32 <alignment>, i1 <from>)
776 The '``llvm.coro.promise``' intrinsic obtains a pointer to a
777 `coroutine promise`_ given a switched-resume coroutine handle and vice versa.
782 The first argument is a handle to a coroutine if `from` is false. Otherwise,
783 it is a pointer to a coroutine promise.
785 The second argument is an alignment requirements of the promise.
786 If a frontend designated `%promise = alloca i32` as a promise, the alignment
787 argument to `coro.promise` should be the alignment of `i32` on the target
788 platform. If a frontend designated `%promise = alloca i32, align 16` as a
789 promise, the alignment argument should be 16.
790 This argument only accepts constants.
792 The third argument is a boolean indicating a direction of the transformation.
793 If `from` is true, the intrinsic returns a coroutine handle given a pointer
794 to a promise. If `from` is false, the intrinsics return a pointer to a promise
795 from a coroutine handle. This argument only accepts constants.
800 Using this intrinsic on a coroutine that does not have a coroutine promise
801 leads to undefined behavior. It is possible to read and modify coroutine
802 promise of the coroutine which is currently executing. The coroutine author and
803 a coroutine user are responsible to makes sure there is no data races.
810 define i8* @f(i32 %n) {
812 %promise = alloca i32
813 %pv = bitcast i32* %promise to i8*
814 ; the second argument to coro.id points to the coroutine promise.
815 %id = call token @llvm.coro.id(i32 0, i8* %pv, i8* null, i8* null)
817 %hdl = call noalias i8* @llvm.coro.begin(token %id, i8* %alloc)
819 store i32 42, i32* %promise ; store something into the promise
826 %hdl = call i8* @f(i32 4) ; starts the coroutine and returns its handle
827 %promise.addr.raw = call i8* @llvm.coro.promise(i8* %hdl, i32 4, i1 false)
828 %promise.addr = bitcast i8* %promise.addr.raw to i32*
829 %val = load i32, i32* %promise.addr ; load a value from the promise
830 call void @print(i32 %val)
831 call void @llvm.coro.destroy(i8* %hdl)
835 .. _coroutine intrinsics:
837 Coroutine Structure Intrinsics
838 ------------------------------
839 Intrinsics described in this section are used within a coroutine to describe
840 the coroutine structure. They should not be used outside of a coroutine.
844 'llvm.coro.size' Intrinsic
845 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
848 declare i32 @llvm.coro.size.i32()
849 declare i64 @llvm.coro.size.i64()
854 The '``llvm.coro.size``' intrinsic returns the number of bytes
855 required to store a `coroutine frame`_. This is only supported for
856 switched-resume coroutines.
866 The `coro.size` intrinsic is lowered to a constant representing the size of
871 'llvm.coro.begin' Intrinsic
872 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
875 declare i8* @llvm.coro.begin(token <id>, i8* <mem>)
880 The '``llvm.coro.begin``' intrinsic returns an address of the coroutine frame.
885 The first argument is a token returned by a call to '``llvm.coro.id``'
886 identifying the coroutine.
888 The second argument is a pointer to a block of memory where coroutine frame
889 will be stored if it is allocated dynamically. This pointer is ignored
890 for returned-continuation coroutines.
895 Depending on the alignment requirements of the objects in the coroutine frame
896 and/or on the codegen compactness reasons the pointer returned from `coro.begin`
897 may be at offset to the `%mem` argument. (This could be beneficial if
898 instructions that express relative access to data can be more compactly encoded
899 with small positive and negative offsets).
901 A frontend should emit exactly one `coro.begin` intrinsic per coroutine.
905 'llvm.coro.free' Intrinsic
906 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
909 declare i8* @llvm.coro.free(token %id, i8* <frame>)
914 The '``llvm.coro.free``' intrinsic returns a pointer to a block of memory where
915 coroutine frame is stored or `null` if this instance of a coroutine did not use
916 dynamically allocated memory for its coroutine frame. This intrinsic is not
917 supported for returned-continuation coroutines.
922 The first argument is a token returned by a call to '``llvm.coro.id``'
923 identifying the coroutine.
925 The second argument is a pointer to the coroutine frame. This should be the same
926 pointer that was returned by prior `coro.begin` call.
928 Example (custom deallocation function):
929 """""""""""""""""""""""""""""""""""""""
934 %mem = call i8* @llvm.coro.free(token %id, i8* %frame)
935 %mem_not_null = icmp ne i8* %mem, null
936 br i1 %mem_not_null, label %if.then, label %if.end
938 call void @CustomFree(i8* %mem)
943 Example (standard deallocation functions):
944 """"""""""""""""""""""""""""""""""""""""""
949 %mem = call i8* @llvm.coro.free(token %id, i8* %frame)
950 call void @free(i8* %mem)
955 'llvm.coro.alloc' Intrinsic
956 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
959 declare i1 @llvm.coro.alloc(token <id>)
964 The '``llvm.coro.alloc``' intrinsic returns `true` if dynamic allocation is
965 required to obtain a memory for the coroutine frame and `false` otherwise.
966 This is not supported for returned-continuation coroutines.
971 The first argument is a token returned by a call to '``llvm.coro.id``'
972 identifying the coroutine.
977 A frontend should emit at most one `coro.alloc` intrinsic per coroutine.
978 The intrinsic is used to suppress dynamic allocation of the coroutine frame
987 %id = call token @llvm.coro.id(i32 0, i8* null, i8* null, i8* null)
988 %dyn.alloc.required = call i1 @llvm.coro.alloc(token %id)
989 br i1 %dyn.alloc.required, label %coro.alloc, label %coro.begin
992 %frame.size = call i32 @llvm.coro.size()
993 %alloc = call i8* @MyAlloc(i32 %frame.size)
997 %phi = phi i8* [ null, %entry ], [ %alloc, %coro.alloc ]
998 %frame = call i8* @llvm.coro.begin(token %id, i8* %phi)
1002 'llvm.coro.noop' Intrinsic
1003 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1006 declare i8* @llvm.coro.noop()
1011 The '``llvm.coro.noop``' intrinsic returns an address of the coroutine frame of
1012 a coroutine that does nothing when resumed or destroyed.
1022 This intrinsic is lowered to refer to a private constant coroutine frame. The
1023 resume and destroy handlers for this frame are empty functions that do nothing.
1024 Note that in different translation units llvm.coro.noop may return different pointers.
1028 'llvm.coro.frame' Intrinsic
1029 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1032 declare i8* @llvm.coro.frame()
1037 The '``llvm.coro.frame``' intrinsic returns an address of the coroutine frame of
1038 the enclosing coroutine.
1048 This intrinsic is lowered to refer to the `coro.begin`_ instruction. This is
1049 a frontend convenience intrinsic that makes it easier to refer to the
1054 'llvm.coro.id' Intrinsic
1055 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1058 declare token @llvm.coro.id(i32 <align>, i8* <promise>, i8* <coroaddr>,
1064 The '``llvm.coro.id``' intrinsic returns a token identifying a
1065 switched-resume coroutine.
1070 The first argument provides information on the alignment of the memory returned
1071 by the allocation function and given to `coro.begin` by the first argument. If
1072 this argument is 0, the memory is assumed to be aligned to 2 * sizeof(i8*).
1073 This argument only accepts constants.
1075 The second argument, if not `null`, designates a particular alloca instruction
1076 to be a `coroutine promise`_.
1078 The third argument is `null` coming out of the frontend. The CoroEarly pass sets
1079 this argument to point to the function this coro.id belongs to.
1081 The fourth argument is `null` before coroutine is split, and later is replaced
1082 to point to a private global constant array containing function pointers to
1083 outlined resume and destroy parts of the coroutine.
1089 The purpose of this intrinsic is to tie together `coro.id`, `coro.alloc` and
1090 `coro.begin` belonging to the same coroutine to prevent optimization passes from
1091 duplicating any of these instructions unless entire body of the coroutine is
1094 A frontend should emit exactly one `coro.id` intrinsic per coroutine.
1098 'llvm.coro.id.retcon' Intrinsic
1099 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1102 declare token @llvm.coro.id.retcon(i32 <size>, i32 <align>, i8* <buffer>,
1103 i8* <continuation prototype>,
1104 i8* <alloc>, i8* <dealloc>)
1109 The '``llvm.coro.id.retcon``' intrinsic returns a token identifying a
1110 multiple-suspend returned-continuation coroutine.
1112 The 'result-type sequence' of the coroutine is defined as follows:
1114 - if the return type of the coroutine function is ``void``, it is the
1117 - if the return type of the coroutine function is a ``struct``, it is the
1118 element types of that ``struct`` in order;
1120 - otherwise, it is just the return type of the coroutine function.
1122 The first element of the result-type sequence must be a pointer type;
1123 continuation functions will be coerced to this type. The rest of
1124 the sequence are the 'yield types', and any suspends in the coroutine
1125 must take arguments of these types.
1130 The first and second arguments are the expected size and alignment of
1131 the buffer provided as the third argument. They must be constant.
1133 The fourth argument must be a reference to a global function, called
1134 the 'continuation prototype function'. The type, calling convention,
1135 and attributes of any continuation functions will be taken from this
1136 declaration. The return type of the prototype function must match the
1137 return type of the current function. The first parameter type must be
1138 a pointer type. The second parameter type must be an integer type;
1139 it will be used only as a boolean flag.
1141 The fifth argument must be a reference to a global function that will
1142 be used to allocate memory. It may not fail, either by returning null
1143 or throwing an exception. It must take an integer and return a pointer.
1145 The sixth argument must be a reference to a global function that will
1146 be used to deallocate memory. It must take a pointer and return ``void``.
1148 'llvm.coro.id.retcon.once' Intrinsic
1149 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1152 declare token @llvm.coro.id.retcon.once(i32 <size>, i32 <align>, i8* <buffer>,
1154 i8* <alloc>, i8* <dealloc>)
1159 The '``llvm.coro.id.retcon.once``' intrinsic returns a token identifying a
1160 unique-suspend returned-continuation coroutine.
1165 As for ``llvm.core.id.retcon``, except that the return type of the
1166 continuation prototype must be `void` instead of matching the
1167 coroutine's return type.
1171 'llvm.coro.end' Intrinsic
1172 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1175 declare i1 @llvm.coro.end(i8* <handle>, i1 <unwind>)
1180 The '``llvm.coro.end``' marks the point where execution of the resume part of
1181 the coroutine should end and control should return to the caller.
1187 The first argument should refer to the coroutine handle of the enclosing
1188 coroutine. A frontend is allowed to supply null as the first parameter, in this
1189 case `coro-early` pass will replace the null with an appropriate coroutine
1192 The second argument should be `true` if this coro.end is in the block that is
1193 part of the unwind sequence leaving the coroutine body due to an exception and
1198 The purpose of this intrinsic is to allow frontends to mark the cleanup and
1199 other code that is only relevant during the initial invocation of the coroutine
1200 and should not be present in resume and destroy parts.
1202 In returned-continuation lowering, ``llvm.coro.end`` fully destroys the
1203 coroutine frame. If the second argument is `false`, it also returns from
1204 the coroutine with a null continuation pointer, and the next instruction
1205 will be unreachable. If the second argument is `true`, it falls through
1206 so that the following logic can resume unwinding. In a yield-once
1207 coroutine, reaching a non-unwind ``llvm.coro.end`` without having first
1208 reached a ``llvm.coro.suspend.retcon`` has undefined behavior.
1210 The remainder of this section describes the behavior under switched-resume
1213 This intrinsic is lowered when a coroutine is split into
1214 the start, resume and destroy parts. In the start part, it is a no-op,
1215 in resume and destroy parts, it is replaced with `ret void` instruction and
1216 the rest of the block containing `coro.end` instruction is discarded.
1217 In landing pads it is replaced with an appropriate instruction to unwind to
1218 caller. The handling of coro.end differs depending on whether the target is
1219 using landingpad or WinEH exception model.
1221 For landingpad based exception model, it is expected that frontend uses the
1222 `coro.end`_ intrinsic as follows:
1224 .. code-block:: llvm
1227 %InResumePart = call i1 @llvm.coro.end(i8* null, i1 true)
1228 br i1 %InResumePart, label %eh.resume, label %cleanup.cont
1231 ; rest of the cleanup
1234 %exn = load i8*, i8** %exn.slot, align 8
1235 %sel = load i32, i32* %ehselector.slot, align 4
1236 %lpad.val = insertvalue { i8*, i32 } undef, i8* %exn, 0
1237 %lpad.val29 = insertvalue { i8*, i32 } %lpad.val, i32 %sel, 1
1238 resume { i8*, i32 } %lpad.val29
1240 The `CoroSpit` pass replaces `coro.end` with ``True`` in the resume functions,
1241 thus leading to immediate unwind to the caller, whereas in start function it
1242 is replaced with ``False``, thus allowing to proceed to the rest of the cleanup
1243 code that is only needed during initial invocation of the coroutine.
1245 For Windows Exception handling model, a frontend should attach a funclet bundle
1246 referring to an enclosing cleanuppad as follows:
1248 .. code-block:: llvm
1251 %tok = cleanuppad within none []
1252 %unused = call i1 @llvm.coro.end(i8* null, i1 true) [ "funclet"(token %tok) ]
1253 cleanupret from %tok unwind label %RestOfTheCleanup
1255 The `CoroSplit` pass, if the funclet bundle is present, will insert
1256 ``cleanupret from %tok unwind to caller`` before
1257 the `coro.end`_ intrinsic and will remove the rest of the block.
1259 The following table summarizes the handling of `coro.end`_ intrinsic.
1261 +--------------------------+-------------------+-------------------------------+
1262 | | In Start Function | In Resume/Destroy Functions |
1263 +--------------------------+-------------------+-------------------------------+
1264 |unwind=false | nothing |``ret void`` |
1265 +------------+-------------+-------------------+-------------------------------+
1266 | | WinEH | nothing |``cleanupret unwind to caller``|
1267 |unwind=true +-------------+-------------------+-------------------------------+
1268 | | Landingpad | nothing | nothing |
1269 +------------+-------------+-------------------+-------------------------------+
1274 'llvm.coro.suspend' Intrinsic
1275 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1278 declare i8 @llvm.coro.suspend(token <save>, i1 <final>)
1283 The '``llvm.coro.suspend``' marks the point where execution of a
1284 switched-resume coroutine is suspended and control is returned back
1285 to the caller. Conditional branches consuming the result of this
1286 intrinsic lead to basic blocks where coroutine should proceed when
1287 suspended (-1), resumed (0) or destroyed (1).
1292 The first argument refers to a token of `coro.save` intrinsic that marks the
1293 point when coroutine state is prepared for suspension. If `none` token is passed,
1294 the intrinsic behaves as if there were a `coro.save` immediately preceding
1295 the `coro.suspend` intrinsic.
1297 The second argument indicates whether this suspension point is `final`_.
1298 The second argument only accepts constants. If more than one suspend point is
1299 designated as final, the resume and destroy branches should lead to the same
1302 Example (normal suspend point):
1303 """""""""""""""""""""""""""""""
1305 .. code-block:: llvm
1307 %0 = call i8 @llvm.coro.suspend(token none, i1 false)
1308 switch i8 %0, label %suspend [i8 0, label %resume
1309 i8 1, label %cleanup]
1311 Example (final suspend point):
1312 """"""""""""""""""""""""""""""
1314 .. code-block:: llvm
1317 %s.final = call i8 @llvm.coro.suspend(token none, i1 true)
1318 switch i8 %s.final, label %suspend [i8 0, label %trap
1319 i8 1, label %cleanup]
1321 call void @llvm.trap()
1327 If a coroutine that was suspended at the suspend point marked by this intrinsic
1328 is resumed via `coro.resume`_ the control will transfer to the basic block
1329 of the 0-case. If it is resumed via `coro.destroy`_, it will proceed to the
1330 basic block indicated by the 1-case. To suspend, coroutine proceed to the
1333 If suspend intrinsic is marked as final, it can consider the `true` branch
1334 unreachable and can perform optimizations that can take advantage of that fact.
1338 'llvm.coro.save' Intrinsic
1339 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1342 declare token @llvm.coro.save(i8* <handle>)
1347 The '``llvm.coro.save``' marks the point where a coroutine need to update its
1348 state to prepare for resumption to be considered suspended (and thus eligible
1354 The first argument points to a coroutine handle of the enclosing coroutine.
1359 Whatever coroutine state changes are required to enable resumption of
1360 the coroutine from the corresponding suspend point should be done at the point
1361 of `coro.save` intrinsic.
1366 Separate save and suspend points are necessary when a coroutine is used to
1367 represent an asynchronous control flow driven by callbacks representing
1368 completions of asynchronous operations.
1370 In such a case, a coroutine should be ready for resumption prior to a call to
1371 `async_op` function that may trigger resumption of a coroutine from the same or
1372 a different thread possibly prior to `async_op` call returning control back
1375 .. code-block:: llvm
1377 %save1 = call token @llvm.coro.save(i8* %hdl)
1378 call void @async_op1(i8* %hdl)
1379 %suspend1 = call i1 @llvm.coro.suspend(token %save1, i1 false)
1380 switch i8 %suspend1, label %suspend [i8 0, label %resume1
1381 i8 1, label %cleanup]
1383 .. _coro.suspend.retcon:
1385 'llvm.coro.suspend.retcon' Intrinsic
1386 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1389 declare i1 @llvm.coro.suspend.retcon(...)
1394 The '``llvm.coro.suspend.retcon``' intrinsic marks the point where
1395 execution of a returned-continuation coroutine is suspended and control
1396 is returned back to the caller.
1398 `llvm.coro.suspend.retcon`` does not support separate save points;
1399 they are not useful when the continuation function is not locally
1400 accessible. That would be a more appropriate feature for a ``passcon``
1401 lowering that is not yet implemented.
1406 The types of the arguments must exactly match the yielded-types sequence
1407 of the coroutine. They will be turned into return values from the ramp
1408 and continuation functions, along with the next continuation function.
1413 The result of the intrinsic indicates whether the coroutine should resume
1414 abnormally (non-zero).
1416 In a normal coroutine, it is undefined behavior if the coroutine executes
1417 a call to ``llvm.coro.suspend.retcon`` after resuming abnormally.
1419 In a yield-once coroutine, it is undefined behavior if the coroutine
1420 executes a call to ``llvm.coro.suspend.retcon`` after resuming in any way.
1424 'llvm.coro.param' Intrinsic
1425 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1428 declare i1 @llvm.coro.param(i8* <original>, i8* <copy>)
1433 The '``llvm.coro.param``' is used by a frontend to mark up the code used to
1434 construct and destruct copies of the parameters. If the optimizer discovers that
1435 a particular parameter copy is not used after any suspends, it can remove the
1436 construction and destruction of the copy by replacing corresponding coro.param
1437 with `i1 false` and replacing any use of the `copy` with the `original`.
1442 The first argument points to an `alloca` storing the value of a parameter to a
1445 The second argument points to an `alloca` storing the value of the copy of that
1451 The optimizer is free to always replace this intrinsic with `i1 true`.
1453 The optimizer is also allowed to replace it with `i1 false` provided that the
1454 parameter copy is only used prior to control flow reaching any of the suspend
1455 points. The code that would be DCE'd if the `coro.param` is replaced with
1456 `i1 false` is not considered to be a use of the parameter copy.
1458 The frontend can emit this intrinsic if its language rules allow for this
1463 Consider the following example. A coroutine takes two parameters `a` and `b`
1464 that has a destructor and a move constructor.
1468 struct A { ~A(); A(A&&); bool foo(); void bar(); };
1470 task<int> f(A a, A b) {
1475 co_await read_async(); // introduces suspend point
1479 Note that, uses of `b` is used after a suspend point and thus must be copied
1480 into a coroutine frame, whereas `a` does not have to, since it never used
1483 A frontend can create parameter copies for `a` and `b` as follows:
1485 .. code-block:: text
1487 task<int> f(A a', A b') {
1490 // move parameters to its copies
1491 if (coro.param(a', a)) A::A(a, A&& a');
1492 if (coro.param(b', b)) A::A(b, A&& b');
1494 // destroy parameters copies
1495 if (coro.param(a', a)) A::~A(a);
1496 if (coro.param(b', b)) A::~A(b);
1499 The optimizer can replace coro.param(a',a) with `i1 false` and replace all uses
1500 of `a` with `a'`, since it is not used after suspend.
1502 The optimizer must replace coro.param(b', b) with `i1 true`, since `b` is used
1503 after suspend and therefore, it has to reside in the coroutine frame.
1505 Coroutine Transformation Passes
1506 ===============================
1509 The pass CoroEarly lowers coroutine intrinsics that hide the details of the
1510 structure of the coroutine frame, but, otherwise not needed to be preserved to
1511 help later coroutine passes. This pass lowers `coro.frame`_, `coro.done`_,
1512 and `coro.promise`_ intrinsics.
1518 The pass CoroSplit buides coroutine frame and outlines resume and destroy parts
1519 into separate functions.
1523 The pass CoroElide examines if the inlined coroutine is eligible for heap
1524 allocation elision optimization. If so, it replaces
1525 `coro.begin` intrinsic with an address of a coroutine frame placed on its caller
1526 and replaces `coro.alloc` and `coro.free` intrinsics with `false` and `null`
1527 respectively to remove the deallocation code.
1528 This pass also replaces `coro.resume` and `coro.destroy` intrinsics with direct
1529 calls to resume and destroy functions for a particular coroutine where possible.
1533 This pass runs late to lower all coroutine related intrinsics not replaced by
1536 Areas Requiring Attention
1537 =========================
1538 #. A coroutine frame is bigger than it could be. Adding stack packing and stack
1539 coloring like optimization on the coroutine frame will result in tighter
1542 #. Take advantage of the lifetime intrinsics for the data that goes into the
1543 coroutine frame. Leave lifetime intrinsics as is for the data that stays in
1546 #. The CoroElide optimization pass relies on coroutine ramp function to be
1547 inlined. It would be beneficial to split the ramp function further to
1548 increase the chance that it will get inlined into its caller.
1550 #. Design a convention that would make it possible to apply coroutine heap
1551 elision optimization across ABI boundaries.
1553 #. Cannot handle coroutines with `inalloca` parameters (used in x86 on Windows).
1555 #. Alignment is ignored by coro.begin and coro.free intrinsics.
1557 #. Make required changes to make sure that coroutine optimizations work with
1560 #. More tests, more tests, more tests