1 =====================================
3 =====================================
10 Compatibility across LLVM releases is not guaranteed.
17 LLVM coroutines are functions that have one or more `suspend points`_.
18 When a suspend point is reached, the execution of a coroutine is suspended and
19 control is returned back to its caller. A suspended coroutine can be resumed
20 to continue execution from the last suspend point or it can be destroyed.
22 In the following example, we call function `f` (which may or may not be a
23 coroutine itself) that returns a handle to a suspended coroutine
24 (**coroutine handle**) that is used by `main` to resume the coroutine twice and
31 %hdl = call ptr @f(i32 4)
32 call void @llvm.coro.resume(ptr %hdl)
33 call void @llvm.coro.resume(ptr %hdl)
34 call void @llvm.coro.destroy(ptr %hdl)
40 In addition to the function stack frame which exists when a coroutine is
41 executing, there is an additional region of storage that contains objects that
42 keep the coroutine state when a coroutine is suspended. This region of storage
43 is called the **coroutine frame**. It is created when a coroutine is called
44 and destroyed when a coroutine either runs to completion or is destroyed
47 LLVM currently supports two styles of coroutine lowering. These styles
48 support substantially different sets of features, have substantially
49 different ABIs, and expect substantially different patterns of frontend
50 code generation. However, the styles also have a great deal in common.
52 In all cases, an LLVM coroutine is initially represented as an ordinary LLVM
53 function that has calls to `coroutine intrinsics`_ defining the structure of
54 the coroutine. The coroutine function is then, in the most general case,
55 rewritten by the coroutine lowering passes to become the "ramp function",
56 the initial entrypoint of the coroutine, which executes until a suspend point
57 is first reached. The remainder of the original coroutine function is split
58 out into some number of "resume functions". Any state which must persist
59 across suspensions is stored in the coroutine frame. The resume functions
60 must somehow be able to handle either a "normal" resumption, which continues
61 the normal execution of the coroutine, or an "abnormal" resumption, which
62 must unwind the coroutine without attempting to suspend it.
64 Switched-Resume Lowering
65 ------------------------
67 In LLVM's standard switched-resume lowering, signaled by the use of
68 `llvm.coro.id`, the coroutine frame is stored as part of a "coroutine
69 object" which represents a handle to a particular invocation of the
70 coroutine. All coroutine objects support a common ABI allowing certain
71 features to be used without knowing anything about the coroutine's
74 - A coroutine object can be queried to see if it has reached completion
75 with `llvm.coro.done`.
77 - A coroutine object can be resumed normally if it has not already reached
78 completion with `llvm.coro.resume`.
80 - A coroutine object can be destroyed, invalidating the coroutine object,
81 with `llvm.coro.destroy`. This must be done separately even if the
82 coroutine has reached completion normally.
84 - "Promise" storage, which is known to have a certain size and alignment,
85 can be projected out of the coroutine object with `llvm.coro.promise`.
86 The coroutine implementation must have been compiled to define a promise
87 of the same size and alignment.
89 In general, interacting with a coroutine object in any of these ways while
90 it is running has undefined behavior.
92 The coroutine function is split into three functions, representing three
93 different ways that control can enter the coroutine:
95 1. the ramp function that is initially invoked, which takes arbitrary
96 arguments and returns a pointer to the coroutine object;
98 2. a coroutine resume function that is invoked when the coroutine is resumed,
99 which takes a pointer to the coroutine object and returns `void`;
101 3. a coroutine destroy function that is invoked when the coroutine is
102 destroyed, which takes a pointer to the coroutine object and returns
105 Because the resume and destroy functions are shared across all suspend
106 points, suspend points must store the index of the active suspend in
107 the coroutine object, and the resume/destroy functions must switch over
108 that index to get back to the correct point. Hence the name of this
111 Pointers to the resume and destroy functions are stored in the coroutine
112 object at known offsets which are fixed for all coroutines. A completed
113 coroutine is represented with a null resume function.
115 There is a somewhat complex protocol of intrinsics for allocating and
116 deallocating the coroutine object. It is complex in order to allow the
117 allocation to be elided due to inlining. This protocol is discussed
118 in further detail below.
120 The frontend may generate code to call the coroutine function directly;
121 this will become a call to the ramp function and will return a pointer
122 to the coroutine object. The frontend should always resume or destroy
123 the coroutine using the corresponding intrinsics.
125 Returned-Continuation Lowering
126 ------------------------------
128 In returned-continuation lowering, signaled by the use of
129 `llvm.coro.id.retcon` or `llvm.coro.id.retcon.once`, some aspects of
130 the ABI must be handled more explicitly by the frontend.
132 In this lowering, every suspend point takes a list of "yielded values"
133 which are returned back to the caller along with a function pointer,
134 called the continuation function. The coroutine is resumed by simply
135 calling this continuation function pointer. The original coroutine
136 is divided into the ramp function and then an arbitrary number of
137 these continuation functions, one for each suspend point.
139 LLVM actually supports two closely-related returned-continuation
142 - In normal returned-continuation lowering, the coroutine may suspend
143 itself multiple times. This means that a continuation function
144 itself returns another continuation pointer, as well as a list of
147 The coroutine indicates that it has run to completion by returning
148 a null continuation pointer. Any yielded values will be `undef`
151 - In yield-once returned-continuation lowering, the coroutine must
152 suspend itself exactly once (or throw an exception). The ramp
153 function returns a continuation function pointer and yielded
154 values, the continuation function may optionally return ordinary
155 results when the coroutine has run to completion.
157 The coroutine frame is maintained in a fixed-size buffer that is
158 passed to the `coro.id` intrinsic, which guarantees a certain size
159 and alignment statically. The same buffer must be passed to the
160 continuation function(s). The coroutine will allocate memory if the
161 buffer is insufficient, in which case it will need to store at
162 least that pointer in the buffer; therefore the buffer must always
163 be at least pointer-sized. How the coroutine uses the buffer may
164 vary between suspend points.
166 In addition to the buffer pointer, continuation functions take an
167 argument indicating whether the coroutine is being resumed normally
168 (zero) or abnormally (non-zero).
170 LLVM is currently ineffective at statically eliminating allocations
171 after fully inlining returned-continuation coroutines into a caller.
172 This may be acceptable if LLVM's coroutine support is primarily being
173 used for low-level lowering and inlining is expected to be applied
174 earlier in the pipeline.
179 In async-continuation lowering, signaled by the use of `llvm.coro.id.async`,
180 handling of control-flow must be handled explicitly by the frontend.
182 In this lowering, a coroutine is assumed to take the current `async context` as
183 one of its arguments (the argument position is determined by
184 `llvm.coro.id.async`). It is used to marshal arguments and return values of the
185 coroutine. Therefore an async coroutine returns `void`.
189 define swiftcc void @async_coroutine(ptr %async.ctxt, ptr, ptr) {
192 Values live across a suspend point need to be stored in the coroutine frame to
193 be available in the continuation function. This frame is stored as a tail to the
196 Every suspend point takes an `context projection function` argument which
197 describes how-to obtain the continuations `async context` and every suspend
198 point has an associated `resume function` denoted by the
199 `llvm.coro.async.resume` intrinsic. The coroutine is resumed by calling this
200 `resume function` passing the `async context` as the one of its arguments
201 argument. The `resume function` can restore its (the caller's) `async context`
202 by applying a `context projection function` that is provided by the frontend as
203 a parameter to the `llvm.coro.suspend.async` intrinsic.
208 struct async_context {
209 struct async_context *caller_context;
213 char *context_projection_function(struct async_context *callee_ctxt) {
214 return callee_ctxt->caller_context;
219 %resume_func_ptr = call ptr @llvm.coro.async.resume()
220 call {ptr, ptr, ptr} (ptr, ptr, ...) @llvm.coro.suspend.async(
221 ptr %resume_func_ptr,
222 ptr %context_projection_function
224 The frontend should provide a `async function pointer` struct associated with
225 each async coroutine by `llvm.coro.id.async`'s argument. The initial size and
226 alignment of the `async context` must be provided as arguments to the
227 `llvm.coro.id.async` intrinsic. Lowering will update the size entry with the
228 coroutine frame requirements. The frontend is responsible for allocating the
229 memory for the `async context` but can use the `async function pointer` struct
230 to obtain the required size.
234 struct async_function_pointer {
235 uint32_t relative_function_pointer_to_async_impl;
236 uint32_t context_size;
239 Lowering will split an async coroutine into a ramp function and one resume
240 function per suspend point.
242 How control-flow is passed between caller, suspension point, and back to
243 resume function is left up to the frontend.
245 The suspend point takes a function and its arguments. The function is intended
246 to model the transfer to the callee function. It will be tail called by
247 lowering and therefore must have the same signature and calling convention as
252 call {ptr, ptr, ptr} (ptr, ptr, ...) @llvm.coro.suspend.async(
253 ptr %resume_func_ptr,
254 ptr %context_projection_function,
255 ptr %suspend_function,
256 ptr %arg1, ptr %arg2, i8 %arg3)
258 Coroutines by Example
259 =====================
261 The examples below are all of switched-resume coroutines.
263 Coroutine Representation
264 ------------------------
266 Let's look at an example of an LLVM coroutine with the behavior sketched
267 by the following pseudo-code.
274 <suspend> // returns a coroutine handle on first suspend
278 This coroutine calls some function `print` with value `n` as an argument and
279 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
280 a `main` shown in the previous section. It will call `print` with values 4, 5
281 and 6 after which the coroutine will be destroyed.
283 The LLVM IR for this coroutine looks like this:
287 define ptr @f(i32 %n) presplitcoroutine {
289 %id = call token @llvm.coro.id(i32 0, ptr null, ptr null, ptr null)
290 %size = call i32 @llvm.coro.size.i32()
291 %alloc = call ptr @malloc(i32 %size)
292 %hdl = call noalias ptr @llvm.coro.begin(token %id, ptr %alloc)
295 %n.val = phi i32 [ %n, %entry ], [ %inc, %loop ]
296 %inc = add nsw i32 %n.val, 1
297 call void @print(i32 %n.val)
298 %0 = call i8 @llvm.coro.suspend(token none, i1 false)
299 switch i8 %0, label %suspend [i8 0, label %loop
300 i8 1, label %cleanup]
302 %mem = call ptr @llvm.coro.free(token %id, ptr %hdl)
303 call void @free(ptr %mem)
306 %unused = call i1 @llvm.coro.end(ptr %hdl, i1 false, token none)
310 The `entry` block establishes the coroutine frame. The `coro.size`_ intrinsic is
311 lowered to a constant representing the size required for the coroutine frame.
312 The `coro.begin`_ intrinsic initializes the coroutine frame and returns the
313 coroutine handle. The second parameter of `coro.begin` is given a block of memory
314 to be used if the coroutine frame needs to be allocated dynamically.
315 The `coro.id`_ intrinsic serves as coroutine identity useful in cases when the
316 `coro.begin`_ intrinsic get duplicated by optimization passes such as
319 The `cleanup` block destroys the coroutine frame. The `coro.free`_ intrinsic,
320 given the coroutine handle, returns a pointer of the memory block to be freed or
321 `null` if the coroutine frame was not allocated dynamically. The `cleanup`
322 block is entered when coroutine runs to completion by itself or destroyed via
323 call to the `coro.destroy`_ intrinsic.
325 The `suspend` block contains code to be executed when coroutine runs to
326 completion or suspended. The `coro.end`_ intrinsic marks the point where
327 a coroutine needs to return control back to the caller if it is not an initial
328 invocation of the coroutine.
330 The `loop` blocks represents the body of the coroutine. The `coro.suspend`_
331 intrinsic in combination with the following switch indicates what happens to
332 control flow when a coroutine is suspended (default case), resumed (case 0) or
335 Coroutine Transformation
336 ------------------------
338 One of the steps of coroutine lowering is building the coroutine frame. The
339 def-use chains are analyzed to determine which objects need be kept alive across
340 suspend points. In the coroutine shown in the previous section, use of virtual register
341 `%inc` is separated from the definition by a suspend point, therefore, it
342 cannot reside on the stack frame since the latter goes away once the coroutine
343 is suspended and control is returned back to the caller. An i32 slot is
344 allocated in the coroutine frame and `%inc` is spilled and reloaded from that
347 We also store addresses of the resume and destroy functions so that the
348 `coro.resume` and `coro.destroy` intrinsics can resume and destroy the coroutine
349 when its identity cannot be determined statically at compile time. For our
350 example, the coroutine frame will be:
354 %f.frame = type { ptr, ptr, i32 }
356 After resume and destroy parts are outlined, function `f` will contain only the
357 code responsible for creation and initialization of the coroutine frame and
358 execution of the coroutine until a suspend point is reached:
362 define ptr @f(i32 %n) {
364 %id = call token @llvm.coro.id(i32 0, ptr null, ptr null, ptr null)
365 %alloc = call noalias ptr @malloc(i32 24)
366 %frame = call noalias ptr @llvm.coro.begin(token %id, ptr %alloc)
367 %1 = getelementptr %f.frame, ptr %frame, i32 0, i32 0
368 store ptr @f.resume, ptr %1
369 %2 = getelementptr %f.frame, ptr %frame, i32 0, i32 1
370 store ptr @f.destroy, ptr %2
372 %inc = add nsw i32 %n, 1
373 %inc.spill.addr = getelementptr inbounds %f.Frame, ptr %FramePtr, i32 0, i32 2
374 store i32 %inc, ptr %inc.spill.addr
375 call void @print(i32 %n)
380 Outlined resume part of the coroutine will reside in function `f.resume`:
384 define internal fastcc void @f.resume(ptr %frame.ptr.resume) {
386 %inc.spill.addr = getelementptr %f.frame, ptr %frame.ptr.resume, i64 0, i32 2
387 %inc.spill = load i32, ptr %inc.spill.addr, align 4
388 %inc = add i32 %inc.spill, 1
389 store i32 %inc, ptr %inc.spill.addr, align 4
390 tail call void @print(i32 %inc)
394 Whereas function `f.destroy` will contain the cleanup code for the coroutine:
398 define internal fastcc void @f.destroy(ptr %frame.ptr.destroy) {
400 tail call void @free(ptr %frame.ptr.destroy)
404 Avoiding Heap Allocations
405 -------------------------
407 A particular coroutine usage pattern, which is illustrated by the `main`
408 function in the overview section, where a coroutine is created, manipulated and
409 destroyed by the same calling function, is common for coroutines implementing
410 RAII idiom and is suitable for allocation elision optimization which avoid
411 dynamic allocation by storing the coroutine frame as a static `alloca` in its
414 In the entry block, we will call `coro.alloc`_ intrinsic that will return `true`
415 when dynamic allocation is required, and `false` if dynamic allocation is
421 %id = call token @llvm.coro.id(i32 0, ptr null, ptr null, ptr null)
422 %need.dyn.alloc = call i1 @llvm.coro.alloc(token %id)
423 br i1 %need.dyn.alloc, label %dyn.alloc, label %coro.begin
425 %size = call i32 @llvm.coro.size.i32()
426 %alloc = call ptr @CustomAlloc(i32 %size)
429 %phi = phi ptr [ null, %entry ], [ %alloc, %dyn.alloc ]
430 %hdl = call noalias ptr @llvm.coro.begin(token %id, ptr %phi)
432 In the cleanup block, we will make freeing the coroutine frame conditional on
433 `coro.free`_ intrinsic. If allocation is elided, `coro.free`_ returns `null`
434 thus skipping the deallocation code:
439 %mem = call ptr @llvm.coro.free(token %id, ptr %hdl)
440 %need.dyn.free = icmp ne ptr %mem, null
441 br i1 %need.dyn.free, label %dyn.free, label %if.end
443 call void @CustomFree(ptr %mem)
448 With allocations and deallocations represented as described as above, after
449 coroutine heap allocation elision optimization, the resulting main will be:
455 call void @print(i32 4)
456 call void @print(i32 5)
457 call void @print(i32 6)
461 Multiple Suspend Points
462 -----------------------
464 Let's consider the coroutine that has more than one suspend point:
477 Matching LLVM code would look like (with the rest of the code remaining the same
478 as the code in the previous section):
483 %n.addr = phi i32 [ %n, %entry ], [ %inc, %loop.resume ]
484 call void @print(i32 %n.addr) #4
485 %2 = call i8 @llvm.coro.suspend(token none, i1 false)
486 switch i8 %2, label %suspend [i8 0, label %loop.resume
487 i8 1, label %cleanup]
489 %inc = add nsw i32 %n.addr, 1
490 %sub = xor i32 %n.addr, -1
491 call void @print(i32 %sub)
492 %3 = call i8 @llvm.coro.suspend(token none, i1 false)
493 switch i8 %3, label %suspend [i8 0, label %loop
494 i8 1, label %cleanup]
496 In this case, the coroutine frame would include a suspend index that will
497 indicate at which suspend point the coroutine needs to resume.
501 %f.frame = type { ptr, ptr, i32, i32 }
503 The resume function will use an index to jump to an appropriate basic block and will look
508 define internal fastcc void @f.Resume(ptr %FramePtr) {
510 %index.addr = getelementptr inbounds %f.Frame, ptr %FramePtr, i64 0, i32 2
511 %index = load i8, ptr %index.addr, align 1
512 %switch = icmp eq i8 %index, 0
513 %n.addr = getelementptr inbounds %f.Frame, ptr %FramePtr, i64 0, i32 3
514 %n = load i32, ptr %n.addr, align 4
516 br i1 %switch, label %loop.resume, label %loop
519 %sub = sub nsw i32 0, %n
520 call void @print(i32 %sub)
523 %inc = add nsw i32 %n, 1
524 store i32 %inc, ptr %n.addr, align 4
525 tail call void @print(i32 %inc)
529 %storemerge = phi i8 [ 0, %loop ], [ 1, %loop.resume ]
530 store i8 %storemerge, ptr %index.addr, align 1
534 If different cleanup code needs to get executed for different suspend points,
535 a similar switch will be in the `f.destroy` function.
539 Using suspend index in a coroutine state and having a switch in `f.resume` and
540 `f.destroy` is one of the possible implementation strategies. We explored
541 another option where a distinct `f.resume1`, `f.resume2`, etc. are created for
542 every suspend point, and instead of storing an index, the resume and destroy
543 function pointers are updated at every suspend. Early testing showed that the
544 current approach is easier on the optimizer than the latter so it is a
545 lowering strategy implemented at the moment.
547 Distinct Save and Suspend
548 -------------------------
550 In the previous example, setting a resume index (or some other state change that
551 needs to happen to prepare a coroutine for resumption) happens at the same time as
552 a suspension of a coroutine. However, in certain cases, it is necessary to control
553 when coroutine is prepared for resumption and when it is suspended.
555 In the following example, a coroutine represents some activity that is driven
556 by completions of asynchronous operations `async_op1` and `async_op2` which get
557 a coroutine handle as a parameter and resume the coroutine once async
558 operation is finished.
565 async_op1(<coroutine-handle>); // will resume once async_op1 completes
570 async_op2(<coroutine-handle>); // will resume once async_op2 completes
577 In this case, coroutine should be ready for resumption prior to a call to
578 `async_op1` and `async_op2`. The `coro.save`_ intrinsic is used to indicate a
579 point when coroutine should be ready for resumption (namely, when a resume index
580 should be stored in the coroutine frame, so that it can be resumed at the
581 correct resume point):
586 %save1 = call token @llvm.coro.save(ptr %hdl)
587 call void @async_op1(ptr %hdl)
588 %suspend1 = call i1 @llvm.coro.suspend(token %save1, i1 false)
589 switch i8 %suspend1, label %suspend [i8 0, label %resume1
590 i8 1, label %cleanup]
592 %save2 = call token @llvm.coro.save(ptr %hdl)
593 call void @async_op2(ptr %hdl)
594 %suspend2 = call i1 @llvm.coro.suspend(token %save2, i1 false)
595 switch i8 %suspend2, label %suspend [i8 0, label %resume2
596 i8 1, label %cleanup]
598 .. _coroutine promise:
603 A coroutine author or a frontend may designate a distinguished `alloca` that can
604 be used to communicate with the coroutine. This distinguished alloca is called
605 **coroutine promise** and is provided as the second parameter to the
606 `coro.id`_ intrinsic.
608 The following coroutine designates a 32 bit integer `promise` and uses it to
609 store the current value produced by a coroutine.
613 define ptr @f(i32 %n) {
615 %promise = alloca i32
616 %id = call token @llvm.coro.id(i32 0, ptr %promise, ptr null, ptr null)
617 %need.dyn.alloc = call i1 @llvm.coro.alloc(token %id)
618 br i1 %need.dyn.alloc, label %dyn.alloc, label %coro.begin
620 %size = call i32 @llvm.coro.size.i32()
621 %alloc = call ptr @malloc(i32 %size)
624 %phi = phi ptr [ null, %entry ], [ %alloc, %dyn.alloc ]
625 %hdl = call noalias ptr @llvm.coro.begin(token %id, ptr %phi)
628 %n.val = phi i32 [ %n, %coro.begin ], [ %inc, %loop ]
629 %inc = add nsw i32 %n.val, 1
630 store i32 %n.val, ptr %promise
631 %0 = call i8 @llvm.coro.suspend(token none, i1 false)
632 switch i8 %0, label %suspend [i8 0, label %loop
633 i8 1, label %cleanup]
635 %mem = call ptr @llvm.coro.free(token %id, ptr %hdl)
636 call void @free(ptr %mem)
639 %unused = call i1 @llvm.coro.end(ptr %hdl, i1 false, token none)
643 A coroutine consumer can rely on the `coro.promise`_ intrinsic to access the
650 %hdl = call ptr @f(i32 4)
651 %promise.addr = call ptr @llvm.coro.promise(ptr %hdl, i32 4, i1 false)
652 %val0 = load i32, ptr %promise.addr
653 call void @print(i32 %val0)
654 call void @llvm.coro.resume(ptr %hdl)
655 %val1 = load i32, ptr %promise.addr
656 call void @print(i32 %val1)
657 call void @llvm.coro.resume(ptr %hdl)
658 %val2 = load i32, ptr %promise.addr
659 call void @print(i32 %val2)
660 call void @llvm.coro.destroy(ptr %hdl)
664 After example in this section is compiled, result of the compilation will be:
670 tail call void @print(i32 4)
671 tail call void @print(i32 5)
672 tail call void @print(i32 6)
682 A coroutine author or a frontend may designate a particular suspend to be final,
683 by setting the second argument of the `coro.suspend`_ intrinsic to `true`.
684 Such a suspend point has two properties:
686 * it is possible to check whether a suspended coroutine is at the final suspend
687 point via `coro.done`_ intrinsic;
689 * a resumption of a coroutine stopped at the final suspend point leads to
690 undefined behavior. The only possible action for a coroutine at a final
691 suspend point is destroying it via `coro.destroy`_ intrinsic.
693 From the user perspective, the final suspend point represents an idea of a
694 coroutine reaching the end. From the compiler perspective, it is an optimization
695 opportunity for reducing number of resume points (and therefore switch cases) in
698 The following is an example of a function that keeps resuming the coroutine
699 until the final suspend point is reached after which point the coroutine is
706 %hdl = call ptr @f(i32 4)
709 call void @llvm.coro.resume(ptr %hdl)
710 %done = call i1 @llvm.coro.done(ptr %hdl)
711 br i1 %done, label %end, label %while
713 call void @llvm.coro.destroy(ptr %hdl)
717 Usually, final suspend point is a frontend injected suspend point that does not
718 correspond to any explicitly authored suspend point of the high level language.
719 For example, for a Python generator that has only one suspend point:
721 .. code-block:: python
727 Python frontend would inject two more suspend points, so that the actual code
732 void* coroutine(int n) {
734 <designate current_value to be coroutine promise>
735 <SUSPEND> // injected suspend point, so that the coroutine starts suspended
736 for (int i = 0; i < n; ++i) {
737 current_value = i; <SUSPEND>; // corresponds to "yield i"
739 <SUSPEND final=true> // injected final suspend point
742 and python iterator `__next__` would look like:
746 int __next__(void* hdl) {
748 if (coro.done(hdl)) throw StopIteration();
749 return *(int*)coro.promise(hdl, 4, false);
756 Coroutine Manipulation Intrinsics
757 ---------------------------------
759 Intrinsics described in this section are used to manipulate an existing
760 coroutine. They can be used in any function which happen to have a pointer
761 to a `coroutine frame`_ or a pointer to a `coroutine promise`_.
765 'llvm.coro.destroy' Intrinsic
766 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
773 declare void @llvm.coro.destroy(ptr <handle>)
778 The '``llvm.coro.destroy``' intrinsic destroys a suspended
779 switched-resume coroutine.
784 The argument is a coroutine handle to a suspended coroutine.
789 When possible, the `coro.destroy` intrinsic is replaced with a direct call to
790 the coroutine destroy function. Otherwise it is replaced with an indirect call
791 based on the function pointer for the destroy function stored in the coroutine
792 frame. Destroying a coroutine that is not suspended leads to undefined behavior.
796 'llvm.coro.resume' Intrinsic
797 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
801 declare void @llvm.coro.resume(ptr <handle>)
806 The '``llvm.coro.resume``' intrinsic resumes a suspended switched-resume coroutine.
811 The argument is a handle to a suspended coroutine.
816 When possible, the `coro.resume` intrinsic is replaced with a direct call to the
817 coroutine resume function. Otherwise it is replaced with an indirect call based
818 on the function pointer for the resume function stored in the coroutine frame.
819 Resuming a coroutine that is not suspended leads to undefined behavior.
823 'llvm.coro.done' Intrinsic
824 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
828 declare i1 @llvm.coro.done(ptr <handle>)
833 The '``llvm.coro.done``' intrinsic checks whether a suspended
834 switched-resume coroutine is at the final suspend point or not.
839 The argument is a handle to a suspended coroutine.
844 Using this intrinsic on a coroutine that does not have a `final suspend`_ point
845 or on a coroutine that is not suspended leads to undefined behavior.
849 'llvm.coro.promise' Intrinsic
850 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
854 declare ptr @llvm.coro.promise(ptr <ptr>, i32 <alignment>, i1 <from>)
859 The '``llvm.coro.promise``' intrinsic obtains a pointer to a
860 `coroutine promise`_ given a switched-resume coroutine handle and vice versa.
865 The first argument is a handle to a coroutine if `from` is false. Otherwise,
866 it is a pointer to a coroutine promise.
868 The second argument is an alignment requirements of the promise.
869 If a frontend designated `%promise = alloca i32` as a promise, the alignment
870 argument to `coro.promise` should be the alignment of `i32` on the target
871 platform. If a frontend designated `%promise = alloca i32, align 16` as a
872 promise, the alignment argument should be 16.
873 This argument only accepts constants.
875 The third argument is a boolean indicating a direction of the transformation.
876 If `from` is true, the intrinsic returns a coroutine handle given a pointer
877 to a promise. If `from` is false, the intrinsics return a pointer to a promise
878 from a coroutine handle. This argument only accepts constants.
883 Using this intrinsic on a coroutine that does not have a coroutine promise
884 leads to undefined behavior. It is possible to read and modify coroutine
885 promise of the coroutine which is currently executing. The coroutine author and
886 a coroutine user are responsible to makes sure there is no data races.
893 define ptr @f(i32 %n) {
895 %promise = alloca i32
896 ; the second argument to coro.id points to the coroutine promise.
897 %id = call token @llvm.coro.id(i32 0, ptr %promise, ptr null, ptr null)
899 %hdl = call noalias ptr @llvm.coro.begin(token %id, ptr %alloc)
901 store i32 42, ptr %promise ; store something into the promise
908 %hdl = call ptr @f(i32 4) ; starts the coroutine and returns its handle
909 %promise.addr = call ptr @llvm.coro.promise(ptr %hdl, i32 4, i1 false)
910 %val = load i32, ptr %promise.addr ; load a value from the promise
911 call void @print(i32 %val)
912 call void @llvm.coro.destroy(ptr %hdl)
916 .. _coroutine intrinsics:
918 Coroutine Structure Intrinsics
919 ------------------------------
920 Intrinsics described in this section are used within a coroutine to describe
921 the coroutine structure. They should not be used outside of a coroutine.
925 'llvm.coro.size' Intrinsic
926 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
929 declare i32 @llvm.coro.size.i32()
930 declare i64 @llvm.coro.size.i64()
935 The '``llvm.coro.size``' intrinsic returns the number of bytes
936 required to store a `coroutine frame`_. This is only supported for
937 switched-resume coroutines.
947 The `coro.size` intrinsic is lowered to a constant representing the size of
952 'llvm.coro.align' Intrinsic
953 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
956 declare i32 @llvm.coro.align.i32()
957 declare i64 @llvm.coro.align.i64()
962 The '``llvm.coro.align``' intrinsic returns the alignment of a `coroutine frame`_.
963 This is only supported for switched-resume coroutines.
973 The `coro.align` intrinsic is lowered to a constant representing the alignment of
978 'llvm.coro.begin' Intrinsic
979 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
982 declare ptr @llvm.coro.begin(token <id>, ptr <mem>)
987 The '``llvm.coro.begin``' intrinsic returns an address of the coroutine frame.
992 The first argument is a token returned by a call to '``llvm.coro.id``'
993 identifying the coroutine.
995 The second argument is a pointer to a block of memory where coroutine frame
996 will be stored if it is allocated dynamically. This pointer is ignored
997 for returned-continuation coroutines.
1002 Depending on the alignment requirements of the objects in the coroutine frame
1003 and/or on the codegen compactness reasons the pointer returned from `coro.begin`
1004 may be at offset to the `%mem` argument. (This could be beneficial if
1005 instructions that express relative access to data can be more compactly encoded
1006 with small positive and negative offsets).
1008 A frontend should emit exactly one `coro.begin` intrinsic per coroutine.
1012 'llvm.coro.free' Intrinsic
1013 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1016 declare ptr @llvm.coro.free(token %id, ptr <frame>)
1021 The '``llvm.coro.free``' intrinsic returns a pointer to a block of memory where
1022 coroutine frame is stored or `null` if this instance of a coroutine did not use
1023 dynamically allocated memory for its coroutine frame. This intrinsic is not
1024 supported for returned-continuation coroutines.
1029 The first argument is a token returned by a call to '``llvm.coro.id``'
1030 identifying the coroutine.
1032 The second argument is a pointer to the coroutine frame. This should be the same
1033 pointer that was returned by prior `coro.begin` call.
1035 Example (custom deallocation function):
1036 """""""""""""""""""""""""""""""""""""""
1038 .. code-block:: llvm
1041 %mem = call ptr @llvm.coro.free(token %id, ptr %frame)
1042 %mem_not_null = icmp ne ptr %mem, null
1043 br i1 %mem_not_null, label %if.then, label %if.end
1045 call void @CustomFree(ptr %mem)
1050 Example (standard deallocation functions):
1051 """"""""""""""""""""""""""""""""""""""""""
1053 .. code-block:: llvm
1056 %mem = call ptr @llvm.coro.free(token %id, ptr %frame)
1057 call void @free(ptr %mem)
1062 'llvm.coro.alloc' Intrinsic
1063 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1066 declare i1 @llvm.coro.alloc(token <id>)
1071 The '``llvm.coro.alloc``' intrinsic returns `true` if dynamic allocation is
1072 required to obtain a memory for the coroutine frame and `false` otherwise.
1073 This is not supported for returned-continuation coroutines.
1078 The first argument is a token returned by a call to '``llvm.coro.id``'
1079 identifying the coroutine.
1084 A frontend should emit at most one `coro.alloc` intrinsic per coroutine.
1085 The intrinsic is used to suppress dynamic allocation of the coroutine frame
1091 .. code-block:: llvm
1094 %id = call token @llvm.coro.id(i32 0, ptr null, ptr null, ptr null)
1095 %dyn.alloc.required = call i1 @llvm.coro.alloc(token %id)
1096 br i1 %dyn.alloc.required, label %coro.alloc, label %coro.begin
1099 %frame.size = call i32 @llvm.coro.size()
1100 %alloc = call ptr @MyAlloc(i32 %frame.size)
1101 br label %coro.begin
1104 %phi = phi ptr [ null, %entry ], [ %alloc, %coro.alloc ]
1105 %frame = call ptr @llvm.coro.begin(token %id, ptr %phi)
1109 'llvm.coro.noop' Intrinsic
1110 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1113 declare ptr @llvm.coro.noop()
1118 The '``llvm.coro.noop``' intrinsic returns an address of the coroutine frame of
1119 a coroutine that does nothing when resumed or destroyed.
1129 This intrinsic is lowered to refer to a private constant coroutine frame. The
1130 resume and destroy handlers for this frame are empty functions that do nothing.
1131 Note that in different translation units llvm.coro.noop may return different pointers.
1135 'llvm.coro.frame' Intrinsic
1136 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1139 declare ptr @llvm.coro.frame()
1144 The '``llvm.coro.frame``' intrinsic returns an address of the coroutine frame of
1145 the enclosing coroutine.
1155 This intrinsic is lowered to refer to the `coro.begin`_ instruction. This is
1156 a frontend convenience intrinsic that makes it easier to refer to the
1161 'llvm.coro.id' Intrinsic
1162 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1165 declare token @llvm.coro.id(i32 <align>, ptr <promise>, ptr <coroaddr>,
1171 The '``llvm.coro.id``' intrinsic returns a token identifying a
1172 switched-resume coroutine.
1177 The first argument provides information on the alignment of the memory returned
1178 by the allocation function and given to `coro.begin` by the first argument. If
1179 this argument is 0, the memory is assumed to be aligned to 2 * sizeof(ptr).
1180 This argument only accepts constants.
1182 The second argument, if not `null`, designates a particular alloca instruction
1183 to be a `coroutine promise`_.
1185 The third argument is `null` coming out of the frontend. The CoroEarly pass sets
1186 this argument to point to the function this coro.id belongs to.
1188 The fourth argument is `null` before coroutine is split, and later is replaced
1189 to point to a private global constant array containing function pointers to
1190 outlined resume and destroy parts of the coroutine.
1196 The purpose of this intrinsic is to tie together `coro.id`, `coro.alloc` and
1197 `coro.begin` belonging to the same coroutine to prevent optimization passes from
1198 duplicating any of these instructions unless entire body of the coroutine is
1201 A frontend should emit exactly one `coro.id` intrinsic per coroutine.
1203 A frontend should emit function attribute `presplitcoroutine` for the coroutine.
1207 'llvm.coro.id.async' Intrinsic
1208 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1211 declare token @llvm.coro.id.async(i32 <context size>, i32 <align>,
1213 ptr <async function pointer>)
1218 The '``llvm.coro.id.async``' intrinsic returns a token identifying an async coroutine.
1223 The first argument provides the initial size of the `async context` as required
1224 from the frontend. Lowering will add to this size the size required by the frame
1225 storage and store that value to the `async function pointer`.
1227 The second argument, is the alignment guarantee of the memory of the
1228 `async context`. The frontend guarantees that the memory will be aligned by this
1231 The third argument is the `async context` argument in the current coroutine.
1233 The fourth argument is the address of the `async function pointer` struct.
1234 Lowering will update the context size requirement in this struct by adding the
1235 coroutine frame size requirement to the initial size requirement as specified by
1236 the first argument of this intrinsic.
1242 A frontend should emit exactly one `coro.id.async` intrinsic per coroutine.
1244 A frontend should emit function attribute `presplitcoroutine` for the coroutine.
1248 'llvm.coro.id.retcon' Intrinsic
1249 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1252 declare token @llvm.coro.id.retcon(i32 <size>, i32 <align>, ptr <buffer>,
1253 ptr <continuation prototype>,
1254 ptr <alloc>, ptr <dealloc>)
1259 The '``llvm.coro.id.retcon``' intrinsic returns a token identifying a
1260 multiple-suspend returned-continuation coroutine.
1262 The 'result-type sequence' of the coroutine is defined as follows:
1264 - if the return type of the coroutine function is ``void``, it is the
1267 - if the return type of the coroutine function is a ``struct``, it is the
1268 element types of that ``struct`` in order;
1270 - otherwise, it is just the return type of the coroutine function.
1272 The first element of the result-type sequence must be a pointer type;
1273 continuation functions will be coerced to this type. The rest of
1274 the sequence are the 'yield types', and any suspends in the coroutine
1275 must take arguments of these types.
1280 The first and second arguments are the expected size and alignment of
1281 the buffer provided as the third argument. They must be constant.
1283 The fourth argument must be a reference to a global function, called
1284 the 'continuation prototype function'. The type, calling convention,
1285 and attributes of any continuation functions will be taken from this
1286 declaration. The return type of the prototype function must match the
1287 return type of the current function. The first parameter type must be
1288 a pointer type. The second parameter type must be an integer type;
1289 it will be used only as a boolean flag.
1291 The fifth argument must be a reference to a global function that will
1292 be used to allocate memory. It may not fail, either by returning null
1293 or throwing an exception. It must take an integer and return a pointer.
1295 The sixth argument must be a reference to a global function that will
1296 be used to deallocate memory. It must take a pointer and return ``void``.
1301 A frontend should emit function attribute `presplitcoroutine` for the coroutine.
1303 'llvm.coro.id.retcon.once' Intrinsic
1304 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1307 declare token @llvm.coro.id.retcon.once(i32 <size>, i32 <align>, ptr <buffer>,
1309 ptr <alloc>, ptr <dealloc>)
1314 The '``llvm.coro.id.retcon.once``' intrinsic returns a token identifying a
1315 unique-suspend returned-continuation coroutine.
1320 As for ``llvm.core.id.retcon``, except that the return type of the
1321 continuation prototype must represent the normal return type of the continuation
1322 (instead of matching the coroutine's return type).
1327 A frontend should emit function attribute `presplitcoroutine` for the coroutine.
1331 'llvm.coro.end' Intrinsic
1332 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1335 declare i1 @llvm.coro.end(ptr <handle>, i1 <unwind>, token <result.token>)
1340 The '``llvm.coro.end``' marks the point where execution of the resume part of
1341 the coroutine should end and control should return to the caller.
1347 The first argument should refer to the coroutine handle of the enclosing
1348 coroutine. A frontend is allowed to supply null as the first parameter, in this
1349 case `coro-early` pass will replace the null with an appropriate coroutine
1352 The second argument should be `true` if this coro.end is in the block that is
1353 part of the unwind sequence leaving the coroutine body due to an exception and
1356 Non-trivial (non-none) token argument can only be specified for unique-suspend
1357 returned-continuation coroutines where it must be a token value produced by
1358 '``llvm.coro.end.results``' intrinsic.
1360 Only none token is allowed for coro.end calls in unwind sections
1364 The purpose of this intrinsic is to allow frontends to mark the cleanup and
1365 other code that is only relevant during the initial invocation of the coroutine
1366 and should not be present in resume and destroy parts.
1368 In returned-continuation lowering, ``llvm.coro.end`` fully destroys the
1369 coroutine frame. If the second argument is `false`, it also returns from
1370 the coroutine with a null continuation pointer, and the next instruction
1371 will be unreachable. If the second argument is `true`, it falls through
1372 so that the following logic can resume unwinding. In a yield-once
1373 coroutine, reaching a non-unwind ``llvm.coro.end`` without having first
1374 reached a ``llvm.coro.suspend.retcon`` has undefined behavior.
1376 The remainder of this section describes the behavior under switched-resume
1379 This intrinsic is lowered when a coroutine is split into
1380 the start, resume and destroy parts. In the start part, it is a no-op,
1381 in resume and destroy parts, it is replaced with `ret void` instruction and
1382 the rest of the block containing `coro.end` instruction is discarded.
1383 In landing pads it is replaced with an appropriate instruction to unwind to
1384 caller. The handling of coro.end differs depending on whether the target is
1385 using landingpad or WinEH exception model.
1387 For landingpad based exception model, it is expected that frontend uses the
1388 `coro.end`_ intrinsic as follows:
1390 .. code-block:: llvm
1393 %InResumePart = call i1 @llvm.coro.end(ptr null, i1 true, token none)
1394 br i1 %InResumePart, label %eh.resume, label %cleanup.cont
1397 ; rest of the cleanup
1400 %exn = load ptr, ptr %exn.slot, align 8
1401 %sel = load i32, ptr %ehselector.slot, align 4
1402 %lpad.val = insertvalue { ptr, i32 } undef, ptr %exn, 0
1403 %lpad.val29 = insertvalue { ptr, i32 } %lpad.val, i32 %sel, 1
1404 resume { ptr, i32 } %lpad.val29
1406 The `CoroSpit` pass replaces `coro.end` with ``True`` in the resume functions,
1407 thus leading to immediate unwind to the caller, whereas in start function it
1408 is replaced with ``False``, thus allowing to proceed to the rest of the cleanup
1409 code that is only needed during initial invocation of the coroutine.
1411 For Windows Exception handling model, a frontend should attach a funclet bundle
1412 referring to an enclosing cleanuppad as follows:
1414 .. code-block:: llvm
1417 %tok = cleanuppad within none []
1418 %unused = call i1 @llvm.coro.end(ptr null, i1 true, token none) [ "funclet"(token %tok) ]
1419 cleanupret from %tok unwind label %RestOfTheCleanup
1421 The `CoroSplit` pass, if the funclet bundle is present, will insert
1422 ``cleanupret from %tok unwind to caller`` before
1423 the `coro.end`_ intrinsic and will remove the rest of the block.
1425 In the unwind path (when the argument is `true`), `coro.end` will mark the coroutine
1426 as done, making it undefined behavior to resume the coroutine again and causing
1427 `llvm.coro.done` to return `true`. This is not necessary in the normal path because
1428 the coroutine will already be marked as done by the final suspend.
1430 The following table summarizes the handling of `coro.end`_ intrinsic.
1432 +--------------------------+------------------------+---------------------------------+
1433 | | In Start Function | In Resume/Destroy Functions |
1434 +--------------------------+------------------------+---------------------------------+
1435 |unwind=false | nothing |``ret void`` |
1436 +------------+-------------+------------------------+---------------------------------+
1437 | | WinEH | mark coroutine as done || ``cleanupret unwind to caller``|
1438 | | | || mark coroutine done |
1439 |unwind=true +-------------+------------------------+---------------------------------+
1440 | | Landingpad | mark coroutine as done | mark coroutine done |
1441 +------------+-------------+------------------------+---------------------------------+
1443 .. _coro.end.results:
1445 'llvm.coro.end.results' Intrinsic
1446 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1449 declare token @llvm.coro.end.results(...)
1454 The '``llvm.coro.end.results``' intrinsic captures values to be returned from
1455 unique-suspend returned-continuation coroutines.
1460 The number of arguments must match the return type of the continuation function:
1462 - if the return type of the continuation function is ``void`` there must be no
1465 - if the return type of the continuation function is a ``struct``, the arguments
1466 will be of element types of that ``struct`` in order;
1468 - otherwise, it is just the return value of the continuation function.
1470 .. code-block:: llvm
1472 define {ptr, ptr} @g(ptr %buffer, ptr %ptr, i8 %val) presplitcoroutine {
1474 %id = call token @llvm.coro.id.retcon.once(i32 8, i32 8, ptr %buffer,
1476 ptr @allocate, ptr @deallocate)
1477 %hdl = call ptr @llvm.coro.begin(token %id, ptr null)
1482 %tok = call token (...) @llvm.coro.end.results(i8 %val)
1483 call i1 @llvm.coro.end(ptr %hdl, i1 0, token %tok)
1488 declare i8 @prototype(ptr, i1 zeroext)
1491 'llvm.coro.end.async' Intrinsic
1492 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1495 declare i1 @llvm.coro.end.async(ptr <handle>, i1 <unwind>, ...)
1500 The '``llvm.coro.end.async``' marks the point where execution of the resume part
1501 of the coroutine should end and control should return to the caller. As part of
1502 its variable tail arguments this instruction allows to specify a function and
1503 the function's arguments that are to be tail called as the last action before
1510 The first argument should refer to the coroutine handle of the enclosing
1511 coroutine. A frontend is allowed to supply null as the first parameter, in this
1512 case `coro-early` pass will replace the null with an appropriate coroutine
1515 The second argument should be `true` if this coro.end is in the block that is
1516 part of the unwind sequence leaving the coroutine body due to an exception and
1519 The third argument if present should specify a function to be called.
1521 If the third argument is present, the remaining arguments are the arguments to
1524 .. code-block:: llvm
1526 call i1 (ptr, i1, ...) @llvm.coro.end.async(
1528 ptr @must_tail_call_return,
1529 ptr %ctxt, ptr %task, ptr %actor)
1535 'llvm.coro.suspend' Intrinsic
1536 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1539 declare i8 @llvm.coro.suspend(token <save>, i1 <final>)
1544 The '``llvm.coro.suspend``' marks the point where execution of a
1545 switched-resume coroutine is suspended and control is returned back
1546 to the caller. Conditional branches consuming the result of this
1547 intrinsic lead to basic blocks where coroutine should proceed when
1548 suspended (-1), resumed (0) or destroyed (1).
1553 The first argument refers to a token of `coro.save` intrinsic that marks the
1554 point when coroutine state is prepared for suspension. If `none` token is passed,
1555 the intrinsic behaves as if there were a `coro.save` immediately preceding
1556 the `coro.suspend` intrinsic.
1558 The second argument indicates whether this suspension point is `final`_.
1559 The second argument only accepts constants. If more than one suspend point is
1560 designated as final, the resume and destroy branches should lead to the same
1563 Example (normal suspend point):
1564 """""""""""""""""""""""""""""""
1566 .. code-block:: llvm
1568 %0 = call i8 @llvm.coro.suspend(token none, i1 false)
1569 switch i8 %0, label %suspend [i8 0, label %resume
1570 i8 1, label %cleanup]
1572 Example (final suspend point):
1573 """"""""""""""""""""""""""""""
1575 .. code-block:: llvm
1578 %s.final = call i8 @llvm.coro.suspend(token none, i1 true)
1579 switch i8 %s.final, label %suspend [i8 0, label %trap
1580 i8 1, label %cleanup]
1582 call void @llvm.trap()
1588 If a coroutine that was suspended at the suspend point marked by this intrinsic
1589 is resumed via `coro.resume`_ the control will transfer to the basic block
1590 of the 0-case. If it is resumed via `coro.destroy`_, it will proceed to the
1591 basic block indicated by the 1-case. To suspend, coroutine proceed to the
1594 If suspend intrinsic is marked as final, it can consider the `true` branch
1595 unreachable and can perform optimizations that can take advantage of that fact.
1599 'llvm.coro.save' Intrinsic
1600 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1603 declare token @llvm.coro.save(ptr <handle>)
1608 The '``llvm.coro.save``' marks the point where a coroutine need to update its
1609 state to prepare for resumption to be considered suspended (and thus eligible
1610 for resumption). It is illegal to merge two '``llvm.coro.save``' calls unless their
1611 '``llvm.coro.suspend``' users are also merged. So '``llvm.coro.save``' is currently
1612 tagged with the `no_merge` function attribute.
1617 The first argument points to a coroutine handle of the enclosing coroutine.
1622 Whatever coroutine state changes are required to enable resumption of
1623 the coroutine from the corresponding suspend point should be done at the point
1624 of `coro.save` intrinsic.
1629 Separate save and suspend points are necessary when a coroutine is used to
1630 represent an asynchronous control flow driven by callbacks representing
1631 completions of asynchronous operations.
1633 In such a case, a coroutine should be ready for resumption prior to a call to
1634 `async_op` function that may trigger resumption of a coroutine from the same or
1635 a different thread possibly prior to `async_op` call returning control back
1638 .. code-block:: llvm
1640 %save1 = call token @llvm.coro.save(ptr %hdl)
1641 call void @async_op1(ptr %hdl)
1642 %suspend1 = call i1 @llvm.coro.suspend(token %save1, i1 false)
1643 switch i8 %suspend1, label %suspend [i8 0, label %resume1
1644 i8 1, label %cleanup]
1646 .. _coro.suspend.async:
1648 'llvm.coro.suspend.async' Intrinsic
1649 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1652 declare {ptr, ptr, ptr} @llvm.coro.suspend.async(
1653 ptr <resume function>,
1654 ptr <context projection function>,
1655 ... <function to call>
1656 ... <arguments to function>)
1661 The '``llvm.coro.suspend.async``' intrinsic marks the point where
1662 execution of an async coroutine is suspended and control is passed to a callee.
1667 The first argument should be the result of the `llvm.coro.async.resume` intrinsic.
1668 Lowering will replace this intrinsic with the resume function for this suspend
1671 The second argument is the `context projection function`. It should describe
1672 how-to restore the `async context` in the continuation function from the first
1673 argument of the continuation function. Its type is `ptr (ptr)`.
1675 The third argument is the function that models transfer to the callee at the
1676 suspend point. It should take 3 arguments. Lowering will `musttail` call this
1679 The fourth to six argument are the arguments for the third argument.
1684 The result of the intrinsic are mapped to the arguments of the resume function.
1685 Execution is suspended at this intrinsic and resumed when the resume function is
1688 .. _coro.prepare.async:
1690 'llvm.coro.prepare.async' Intrinsic
1691 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1694 declare ptr @llvm.coro.prepare.async(ptr <coroutine function>)
1699 The '``llvm.coro.prepare.async``' intrinsic is used to block inlining of the
1700 async coroutine until after coroutine splitting.
1705 The first argument should be an async coroutine of type `void (ptr, ptr, ptr)`.
1706 Lowering will replace this intrinsic with its coroutine function argument.
1708 .. _coro.suspend.retcon:
1710 'llvm.coro.suspend.retcon' Intrinsic
1711 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1714 declare i1 @llvm.coro.suspend.retcon(...)
1719 The '``llvm.coro.suspend.retcon``' intrinsic marks the point where
1720 execution of a returned-continuation coroutine is suspended and control
1721 is returned back to the caller.
1723 `llvm.coro.suspend.retcon`` does not support separate save points;
1724 they are not useful when the continuation function is not locally
1725 accessible. That would be a more appropriate feature for a ``passcon``
1726 lowering that is not yet implemented.
1731 The types of the arguments must exactly match the yielded-types sequence
1732 of the coroutine. They will be turned into return values from the ramp
1733 and continuation functions, along with the next continuation function.
1738 The result of the intrinsic indicates whether the coroutine should resume
1739 abnormally (non-zero).
1741 In a normal coroutine, it is undefined behavior if the coroutine executes
1742 a call to ``llvm.coro.suspend.retcon`` after resuming abnormally.
1744 In a yield-once coroutine, it is undefined behavior if the coroutine
1745 executes a call to ``llvm.coro.suspend.retcon`` after resuming in any way.
1747 .. _coro.await.suspend.void:
1749 'llvm.coro.await.suspend.void' Intrinsic
1750 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1753 declare void @llvm.coro.await.suspend.void(
1756 ptr <await_suspend_function>)
1761 The '``llvm.coro.await.suspend.void``' intrinsic encapsulates C++
1762 `await-suspend` block until it can't interfere with coroutine transform.
1764 The `await_suspend` block of `co_await` is essentially asynchronous
1765 to the execution of the coroutine. Inlining it normally into an unsplit
1766 coroutine can cause miscompilation because the coroutine CFG misrepresents
1767 the true control flow of the program: things that happen in the
1768 await_suspend are not guaranteed to happen prior to the resumption of the
1769 coroutine, and things that happen after the resumption of the coroutine
1770 (including its exit and the potential deallocation of the coroutine frame)
1771 are not guaranteed to happen only after the end of `await_suspend`.
1773 This version of intrinsic corresponds to
1774 '``void awaiter.await_suspend(...)``' variant.
1779 The first argument is a pointer to `awaiter` object.
1781 The second argument is a pointer to the current coroutine's frame.
1783 The third argument is a pointer to the wrapper function encapsulating
1784 `await-suspend` logic. Its signature must be
1786 .. code-block:: llvm
1788 declare void @await_suspend_function(ptr %awaiter, ptr %hdl)
1793 The intrinsic must be used between corresponding `coro.save`_ and
1794 `coro.suspend`_ calls. It is lowered to a direct
1795 `await_suspend_function` call during `CoroSplit`_ pass.
1800 .. code-block:: llvm
1804 %save = call token @llvm.coro.save(ptr %hdl)
1805 call void @llvm.coro.await.suspend.void(
1808 ptr @await_suspend_function)
1809 %suspend = call i8 @llvm.coro.suspend(token %save, i1 false)
1814 %save = call token @llvm.coro.save(ptr %hdl)
1815 ; the call to await_suspend_function can be inlined
1816 call void @await_suspend_function(
1819 %suspend = call i8 @llvm.coro.suspend(token %save, i1 false)
1822 ; wrapper function example
1823 define void @await_suspend_function(ptr %awaiter, ptr %hdl)
1825 %hdl.arg = ... ; construct std::coroutine_handle from %hdl
1826 call void @"Awaiter::await_suspend"(ptr %awaiter, ptr %hdl.arg)
1829 .. _coro.await.suspend.bool:
1831 'llvm.coro.await.suspend.bool' Intrinsic
1832 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1835 declare i1 @llvm.coro.await.suspend.bool(
1838 ptr <await_suspend_function>)
1843 The '``llvm.coro.await.suspend.bool``' intrinsic encapsulates C++
1844 `await-suspend` block until it can't interfere with coroutine transform.
1846 The `await_suspend` block of `co_await` is essentially asynchronous
1847 to the execution of the coroutine. Inlining it normally into an unsplit
1848 coroutine can cause miscompilation because the coroutine CFG misrepresents
1849 the true control flow of the program: things that happen in the
1850 await_suspend are not guaranteed to happen prior to the resumption of the
1851 coroutine, and things that happen after the resumption of the coroutine
1852 (including its exit and the potential deallocation of the coroutine frame)
1853 are not guaranteed to happen only after the end of `await_suspend`.
1855 This version of intrinsic corresponds to
1856 '``bool awaiter.await_suspend(...)``' variant.
1861 The first argument is a pointer to `awaiter` object.
1863 The second argument is a pointer to the current coroutine's frame.
1865 The third argument is a pointer to the wrapper function encapsulating
1866 `await-suspend` logic. Its signature must be
1868 .. code-block:: llvm
1870 declare i1 @await_suspend_function(ptr %awaiter, ptr %hdl)
1875 The intrinsic must be used between corresponding `coro.save`_ and
1876 `coro.suspend`_ calls. It is lowered to a direct
1877 `await_suspend_function` call during `CoroSplit`_ pass.
1879 If `await_suspend_function` call returns `true`, the current coroutine is
1880 immediately resumed.
1885 .. code-block:: llvm
1889 %save = call token @llvm.coro.save(ptr %hdl)
1890 %resume = call i1 @llvm.coro.await.suspend.bool(
1893 ptr @await_suspend_function)
1894 br i1 %resume, %await.suspend.bool, %await.ready
1896 %suspend = call i8 @llvm.coro.suspend(token %save, i1 false)
1899 call void @"Awaiter::await_resume"(ptr %awaiter)
1904 %save = call token @llvm.coro.save(ptr %hdl)
1905 ; the call to await_suspend_function can inlined
1906 %resume = call i1 @await_suspend_function(
1909 br i1 %resume, %await.suspend.bool, %await.ready
1912 ; wrapper function example
1913 define i1 @await_suspend_function(ptr %awaiter, ptr %hdl)
1915 %hdl.arg = ... ; construct std::coroutine_handle from %hdl
1916 %resume = call i1 @"Awaiter::await_suspend"(ptr %awaiter, ptr %hdl.arg)
1919 .. _coro.await.suspend.handle:
1921 'llvm.coro.await.suspend.handle' Intrinsic
1922 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1925 declare void @llvm.coro.await.suspend.handle(
1928 ptr <await_suspend_function>)
1933 The '``llvm.coro.await.suspend.handle``' intrinsic encapsulates C++
1934 `await-suspend` block until it can't interfere with coroutine transform.
1936 The `await_suspend` block of `co_await` is essentially asynchronous
1937 to the execution of the coroutine. Inlining it normally into an unsplit
1938 coroutine can cause miscompilation because the coroutine CFG misrepresents
1939 the true control flow of the program: things that happen in the
1940 await_suspend are not guaranteed to happen prior to the resumption of the
1941 coroutine, and things that happen after the resumption of the coroutine
1942 (including its exit and the potential deallocation of the coroutine frame)
1943 are not guaranteed to happen only after the end of `await_suspend`.
1945 This version of intrinsic corresponds to
1946 '``std::corouine_handle<> awaiter.await_suspend(...)``' variant.
1951 The first argument is a pointer to `awaiter` object.
1953 The second argument is a pointer to the current coroutine's frame.
1955 The third argument is a pointer to the wrapper function encapsulating
1956 `await-suspend` logic. Its signature must be
1958 .. code-block:: llvm
1960 declare ptr @await_suspend_function(ptr %awaiter, ptr %hdl)
1965 The intrinsic must be used between corresponding `coro.save`_ and
1966 `coro.suspend`_ calls. It is lowered to a direct
1967 `await_suspend_function` call during `CoroSplit`_ pass.
1969 `await_suspend_function` must return a pointer to a valid
1970 coroutine frame. The intrinsic will be lowered to a tail call resuming the
1971 returned coroutine frame. It will be marked `musttail` on targets that support
1972 that. Instructions following the intrinsic will become unreachable.
1977 .. code-block:: llvm
1981 %save = call token @llvm.coro.save(ptr %hdl)
1982 call void @llvm.coro.await.suspend.handle(
1985 ptr @await_suspend_function)
1986 %suspend = call i8 @llvm.coro.suspend(token %save, i1 false)
1991 %save = call token @llvm.coro.save(ptr %hdl)
1992 ; the call to await_suspend_function can be inlined
1993 %next = call ptr @await_suspend_function(
1996 musttail call void @llvm.coro.resume(%next)
2000 ; wrapper function example
2001 define ptr @await_suspend_function(ptr %awaiter, ptr %hdl)
2003 %hdl.arg = ... ; construct std::coroutine_handle from %hdl
2004 %hdl.raw = call ptr @"Awaiter::await_suspend"(ptr %awaiter, ptr %hdl.arg)
2005 %hdl.result = ... ; get address of returned coroutine handle
2008 Coroutine Transformation Passes
2009 ===============================
2012 The pass CoroEarly lowers coroutine intrinsics that hide the details of the
2013 structure of the coroutine frame, but, otherwise not needed to be preserved to
2014 help later coroutine passes. This pass lowers `coro.frame`_, `coro.done`_,
2015 and `coro.promise`_ intrinsics.
2021 The pass CoroSplit builds coroutine frame and outlines resume and destroy parts
2022 into separate functions. This pass also lowers `coro.await.suspend.void`_,
2023 `coro.await.suspend.bool`_ and `coro.await.suspend.handle`_ intrinsics.
2028 The pass CoroElide examines if the inlined coroutine is eligible for heap
2029 allocation elision optimization. If so, it replaces
2030 `coro.begin` intrinsic with an address of a coroutine frame placed on its caller
2031 and replaces `coro.alloc` and `coro.free` intrinsics with `false` and `null`
2032 respectively to remove the deallocation code.
2033 This pass also replaces `coro.resume` and `coro.destroy` intrinsics with direct
2034 calls to resume and destroy functions for a particular coroutine where possible.
2038 This pass runs late to lower all coroutine related intrinsics not replaced by
2044 coro_only_destroy_when_complete
2045 -------------------------------
2047 When the coroutine are marked with coro_only_destroy_when_complete, it indicates
2048 the coroutine must reach the final suspend point when it get destroyed.
2050 This attribute only works for switched-resume coroutines now.
2055 '``coro.outside.frame``' Metadata
2056 ---------------------------------
2058 ``coro.outside.frame`` metadata may be attached to an alloca instruction to
2059 to signify that it shouldn't be promoted to the coroutine frame, useful for
2060 filtering allocas out by the frontend when emitting internal control mechanisms.
2061 Additionally, this metadata is only used as a flag, so the associated
2064 .. code-block:: text
2066 %__coro_gro = alloca %struct.GroType, align 1, !coro.outside.frame !0
2071 Areas Requiring Attention
2072 =========================
2073 #. When coro.suspend returns -1, the coroutine is suspended, and it's possible
2074 that the coroutine has already been destroyed (hence the frame has been freed).
2075 We cannot access anything on the frame on the suspend path.
2076 However there is nothing that prevents the compiler from moving instructions
2077 along that path (e.g. LICM), which can lead to use-after-free. At the moment
2078 we disabled LICM for loops that have coro.suspend, but the general problem still
2079 exists and requires a general solution.
2081 #. Take advantage of the lifetime intrinsics for the data that goes into the
2082 coroutine frame. Leave lifetime intrinsics as is for the data that stays in
2085 #. The CoroElide optimization pass relies on coroutine ramp function to be
2086 inlined. It would be beneficial to split the ramp function further to
2087 increase the chance that it will get inlined into its caller.
2089 #. Design a convention that would make it possible to apply coroutine heap
2090 elision optimization across ABI boundaries.
2092 #. Cannot handle coroutines with `inalloca` parameters (used in x86 on Windows).
2094 #. Alignment is ignored by coro.begin and coro.free intrinsics.
2096 #. Make required changes to make sure that coroutine optimizations work with
2099 #. More tests, more tests, more tests