1 =====================================
2 Garbage Collection Safepoints in LLVM
3 =====================================
12 This document describes a set of experimental extensions to LLVM. Use
13 with caution. Because the intrinsics have experimental status,
14 compatibility across LLVM releases is not guaranteed.
16 LLVM currently supports an alternate mechanism for conservative
17 garbage collection support using the ``gcroot`` intrinsic. The mechanism
18 described here shares little in common with the alternate ``gcroot``
19 implementation and it is hoped that this mechanism will eventually
20 replace the gc_root mechanism.
25 To collect dead objects, garbage collectors must be able to identify
26 any references to objects contained within executing code, and,
27 depending on the collector, potentially update them. The collector
28 does not need this information at all points in code - that would make
29 the problem much harder - but only at well-defined points in the
30 execution known as 'safepoints' For most collectors, it is sufficient
31 to track at least one copy of each unique pointer value. However, for
32 a collector which wishes to relocate objects directly reachable from
33 running code, a higher standard is required.
35 One additional challenge is that the compiler may compute intermediate
36 results ("derived pointers") which point outside of the allocation or
37 even into the middle of another allocation. The eventual use of this
38 intermediate value must yield an address within the bounds of the
39 allocation, but such "exterior derived pointers" may be visible to the
40 collector. Given this, a garbage collector can not safely rely on the
41 runtime value of an address to indicate the object it is associated
42 with. If the garbage collector wishes to move any object, the
43 compiler must provide a mapping, for each pointer, to an indication of
46 To simplify the interaction between a collector and the compiled code,
47 most garbage collectors are organized in terms of three abstractions:
48 load barriers, store barriers, and safepoints.
50 #. A load barrier is a bit of code executed immediately after the
51 machine load instruction, but before any use of the value loaded.
52 Depending on the collector, such a barrier may be needed for all
53 loads, merely loads of a particular type (in the original source
54 language), or none at all.
56 #. Analogously, a store barrier is a code fragement that runs
57 immediately before the machine store instruction, but after the
58 computation of the value stored. The most common use of a store
59 barrier is to update a 'card table' in a generational garbage
62 #. A safepoint is a location at which pointers visible to the compiled
63 code (i.e. currently in registers or on the stack) are allowed to
64 change. After the safepoint completes, the actual pointer value
65 may differ, but the 'object' (as seen by the source language)
68 Note that the term 'safepoint' is somewhat overloaded. It refers to
69 both the location at which the machine state is parsable and the
70 coordination protocol involved in bring application threads to a
71 point at which the collector can safely use that information. The
72 term "statepoint" as used in this document refers exclusively to the
75 This document focuses on the last item - compiler support for
76 safepoints in generated code. We will assume that an outside
77 mechanism has decided where to place safepoints. From our
78 perspective, all safepoints will be function calls. To support
79 relocation of objects directly reachable from values in compiled code,
80 the collector must be able to:
82 #. identify every copy of a pointer (including copies introduced by
83 the compiler itself) at the safepoint,
84 #. identify which object each pointer relates to, and
85 #. potentially update each of those copies.
87 This document describes the mechanism by which an LLVM based compiler
88 can provide this information to a language runtime/collector, and
89 ensure that all pointers can be read and updated if desired. The
90 heart of the approach is to construct (or rewrite) the IR in a manner
91 where the possible updates performed by the garbage collector are
92 explicitly visible in the IR. Doing so requires that we:
94 #. create a new SSA value for each potentially relocated pointer, and
95 ensure that no uses of the original (non relocated) value is
96 reachable after the safepoint,
97 #. specify the relocation in a way which is opaque to the compiler to
98 ensure that the optimizer can not introduce new uses of an
99 unrelocated value after a statepoint. This prevents the optimizer
100 from performing unsound optimizations.
101 #. recording a mapping of live pointers (and the allocation they're
102 associated with) for each statepoint.
104 At the most abstract level, inserting a safepoint can be thought of as
105 replacing a call instruction with a call to a multiple return value
106 function which both calls the original target of the call, returns
107 it's result, and returns updated values for any live pointers to
108 garbage collected objects.
110 Note that the task of identifying all live pointers to garbage
111 collected values, transforming the IR to expose a pointer giving the
112 base object for every such live pointer, and inserting all the
113 intrinsics correctly is explicitly out of scope for this document.
114 The recommended approach is to use the :ref:`utility passes
115 <statepoint-utilities>` described below.
117 This abstract function call is concretely represented by a sequence of
118 intrinsic calls known collectively as a "statepoint relocation sequence".
120 Let's consider a simple call in LLVM IR:
124 define i8 addrspace(1)* @test1(i8 addrspace(1)* %obj)
125 gc "statepoint-example" {
127 ret i8 addrspace(1)* %obj
130 Depending on our language we may need to allow a safepoint during the execution
131 of ``foo``. If so, we need to let the collector update local values in the
132 current frame. If we don't, we'll be accessing a potential invalid reference
133 once we eventually return from the call.
135 In this example, we need to relocate the SSA value ``%obj``. Since we can't
136 actually change the value in the SSA value ``%obj``, we need to introduce a new
137 SSA value ``%obj.relocated`` which represents the potentially changed value of
138 ``%obj`` after the safepoint and update any following uses appropriately. The
139 resulting relocation sequence is:
143 define i8 addrspace(1)* @test1(i8 addrspace(1)* %obj)
144 gc "statepoint-example" {
145 %0 = call i32 (void ()*, i32, i32, ...)* @llvm.experimental.gc.statepoint.p0f_isVoidf(void ()* @foo, i32 0, i32 0, i32 5, i32 0, i32 -1, i32 0, i32 0, i32 0, i8 addrspace(1)* %obj)
146 %obj.relocated = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(i32 %0, i32 9, i32 9)
147 ret i8 addrspace(1)* %obj.relocated
150 Ideally, this sequence would have been represented as a M argument, N
151 return value function (where M is the number of values being
152 relocated + the original call arguments and N is the original return
153 value + each relocated value), but LLVM does not easily support such a
156 Instead, the statepoint intrinsic marks the actual site of the
157 safepoint or statepoint. The statepoint returns a token value (which
158 exists only at compile time). To get back the original return value
159 of the call, we use the ``gc.result`` intrinsic. To get the relocation
160 of each pointer in turn, we use the ``gc.relocate`` intrinsic with the
161 appropriate index. Note that both the ``gc.relocate`` and ``gc.result`` are
162 tied to the statepoint. The combination forms a "statepoint relocation
163 sequence" and represents the entitety of a parseable call or 'statepoint'.
165 When lowered, this example would generate the following x86 assembly:
174 movq (%rsp), %rax # This load is redundant (oops!)
178 Each of the potentially relocated values has been spilled to the
179 stack, and a record of that location has been recorded to the
180 :ref:`Stack Map section <stackmap-section>`. If the garbage collector
181 needs to update any of these pointers during the call, it knows
182 exactly what to change.
184 The relevant parts of the StackMap section for our example are:
188 # This describes the call site
189 # Stack Maps: callsite 2882400000
193 # .. 8 entries skipped ..
194 # This entry describes the spill slot which is directly addressable
195 # off RSP with offset 0. Given the value was spilled with a pushq,
197 # Stack Maps: Loc 8: Direct RSP [encoding: .byte 2, .byte 8, .short 7, .int 0]
203 This example was taken from the tests for the :ref:`RewriteStatepointsForGC` utility pass. As such, it's full StackMap can be easily examined with the following command.
207 opt -rewrite-statepoints-for-gc test/Transforms/RewriteStatepointsForGC/basics.ll -S | llc -debug-only=stackmaps
216 'llvm.experimental.gc.statepoint' Intrinsic
217 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
225 @llvm.experimental.gc.statepoint(func_type <target>,
226 i64 <#call args>. i64 <unused>,
227 ... (call parameters),
228 i64 <# deopt args>, ... (deopt parameters),
234 The statepoint intrinsic represents a call which is parse-able by the
240 The 'target' operand is the function actually being called. The
241 target can be specified as either a symbolic LLVM function, or as an
242 arbitrary Value of appropriate function type. Note that the function
243 type must match the signature of the callee and the types of the 'call
244 parameters' arguments.
246 The '#call args' operand is the number of arguments to the actual
247 call. It must exactly match the number of arguments passed in the
248 'call parameters' variable length section.
250 The 'unused' operand is unused and likely to be removed. Please do
253 The 'call parameters' arguments are simply the arguments which need to
254 be passed to the call target. They will be lowered according to the
255 specified calling convention and otherwise handled like a normal call
256 instruction. The number of arguments must exactly match what is
257 specified in '# call args'. The types must match the signature of
260 The 'deopt parameters' arguments contain an arbitrary list of Values
261 which is meaningful to the runtime. The runtime may read any of these
262 values, but is assumed not to modify them. If the garbage collector
263 might need to modify one of these values, it must also be listed in
264 the 'gc pointer' argument list. The '# deopt args' field indicates
265 how many operands are to be interpreted as 'deopt parameters'.
267 The 'gc parameters' arguments contain every pointer to a garbage
268 collector object which potentially needs to be updated by the garbage
269 collector. Note that the argument list must explicitly contain a base
270 pointer for every derived pointer listed. The order of arguments is
271 unimportant. Unlike the other variable length parameter sets, this
272 list is not length prefixed.
277 A statepoint is assumed to read and write all memory. As a result,
278 memory operations can not be reordered past a statepoint. It is
279 illegal to mark a statepoint as being either 'readonly' or 'readnone'.
281 Note that legal IR can not perform any memory operation on a 'gc
282 pointer' argument of the statepoint in a location statically reachable
283 from the statepoint. Instead, the explicitly relocated value (from a
284 ``gc.relocate``) must be used.
286 'llvm.experimental.gc.result' Intrinsic
287 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
295 @llvm.experimental.gc.result(i32 %statepoint_token)
300 ``gc.result`` extracts the result of the original call instruction
301 which was replaced by the ``gc.statepoint``. The ``gc.result``
302 intrinsic is actually a family of three intrinsics due to an
303 implementation limitation. Other than the type of the return value,
304 the semantics are the same.
309 The first and only argument is the ``gc.statepoint`` which starts
310 the safepoint sequence of which this ``gc.result`` is a part.
311 Despite the typing of this as a generic i32, *only* the value defined
312 by a ``gc.statepoint`` is legal here.
317 The ``gc.result`` represents the return value of the call target of
318 the ``statepoint``. The type of the ``gc.result`` must exactly match
319 the type of the target. If the call target returns void, there will
322 A ``gc.result`` is modeled as a 'readnone' pure function. It has no
323 side effects since it is just a projection of the return value of the
324 previous call represented by the ``gc.statepoint``.
326 'llvm.experimental.gc.relocate' Intrinsic
327 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
334 declare <pointer type>
335 @llvm.experimental.gc.relocate(i32 %statepoint_token,
342 A ``gc.relocate`` returns the potentially relocated value of a pointer
348 The first argument is the ``gc.statepoint`` which starts the
349 safepoint sequence of which this ``gc.relocation`` is a part.
350 Despite the typing of this as a generic i32, *only* the value defined
351 by a ``gc.statepoint`` is legal here.
353 The second argument is an index into the statepoints list of arguments
354 which specifies the base pointer for the pointer being relocated.
355 This index must land within the 'gc parameter' section of the
356 statepoint's argument list.
358 The third argument is an index into the statepoint's list of arguments
359 which specify the (potentially) derived pointer being relocated. It
360 is legal for this index to be the same as the second argument
361 if-and-only-if a base pointer is being relocated. This index must land
362 within the 'gc parameter' section of the statepoint's argument list.
367 The return value of ``gc.relocate`` is the potentially relocated value
368 of the pointer specified by it's arguments. It is unspecified how the
369 value of the returned pointer relates to the argument to the
370 ``gc.statepoint`` other than that a) it points to the same source
371 language object with the same offset, and b) the 'based-on'
372 relationship of the newly relocated pointers is a projection of the
373 unrelocated pointers. In particular, the integer value of the pointer
374 returned is unspecified.
376 A ``gc.relocate`` is modeled as a ``readnone`` pure function. It has no
377 side effects since it is just a way to extract information about work
378 done during the actual call modeled by the ``gc.statepoint``.
380 .. _statepoint-stackmap-format:
385 Locations for each pointer value which may need read and/or updated by
386 the runtime or collector are provided via the :ref:`Stack Map format
387 <stackmap-format>` specified in the PatchPoint documentation.
389 Each statepoint generates the following Locations:
391 * Constant which describes number of following deopt *Locations* (not
393 * Variable number of Locations, one for each deopt parameter listed in
394 the IR statepoint (same number as described by previous Constant)
395 * Variable number of Locations pairs, one pair for each unique pointer
396 which needs relocated. The first Location in each pair describes
397 the base pointer for the object. The second is the derived pointer
398 actually being relocated. It is guaranteed that the base pointer
399 must also appear explicitly as a relocation pair if used after the
400 statepoint. There may be fewer pairs then gc parameters in the IR
401 statepoint. Each *unique* pair will occur at least once; duplicates
404 Note that the Locations used in each section may describe the same
405 physical location. e.g. A stack slot may appear as a deopt location,
406 a gc base pointer, and a gc derived pointer.
408 The ID field of the 'StkMapRecord' for a statepoint is meaningless and
409 it's value is explicitly unspecified.
411 The LiveOut section of the StkMapRecord will be empty for a statepoint
414 Safepoint Semantics & Verification
415 ==================================
417 The fundamental correctness property for the compiled code's
418 correctness w.r.t. the garbage collector is a dynamic one. It must be
419 the case that there is no dynamic trace such that a operation
420 involving a potentially relocated pointer is observably-after a
421 safepoint which could relocate it. 'observably-after' is this usage
422 means that an outside observer could observe this sequence of events
423 in a way which precludes the operation being performed before the
426 To understand why this 'observable-after' property is required,
427 consider a null comparison performed on the original copy of a
428 relocated pointer. Assuming that control flow follows the safepoint,
429 there is no way to observe externally whether the null comparison is
430 performed before or after the safepoint. (Remember, the original
431 Value is unmodified by the safepoint.) The compiler is free to make
432 either scheduling choice.
434 The actual correctness property implemented is slightly stronger than
435 this. We require that there be no *static path* on which a
436 potentially relocated pointer is 'observably-after' it may have been
437 relocated. This is slightly stronger than is strictly necessary (and
438 thus may disallow some otherwise valid programs), but greatly
439 simplifies reasoning about correctness of the compiled code.
441 By construction, this property will be upheld by the optimizer if
442 correctly established in the source IR. This is a key invariant of
445 The existing IR Verifier pass has been extended to check most of the
446 local restrictions on the intrinsics mentioned in their respective
447 documentation. The current implementation in LLVM does not check the
448 key relocation invariant, but this is ongoing work on developing such
449 a verifier. Please ask on llvmdev if you're interested in
450 experimenting with the current version.
452 .. _statepoint-utilities:
454 Utility Passes for Safepoint Insertion
455 ======================================
457 .. _RewriteStatepointsForGC:
459 RewriteStatepointsForGC
460 ^^^^^^^^^^^^^^^^^^^^^^^^
462 The pass RewriteStatepointsForGC transforms a functions IR by replacing a
463 ``gc.statepoint`` (with an optional ``gc.result``) with a full relocation
464 sequence, including all required ``gc.relocates``. To function, the pass
465 requires that the GC strategy specified for the function be able to reliably
466 distinguish between GC references and non-GC references in IR it is given.
468 As an example, given this code:
472 define i8 addrspace(1)* @test1(i8 addrspace(1)* %obj)
473 gc "statepoint-example" {
474 call i32 (void ()*, i32, i32, ...)* @llvm.experimental.gc.statepoint.p0f_isVoidf(void ()* @foo, i32 0, i32 0, i32 5, i32 0, i32 -1, i32 0, i32 0, i32 0)
475 ret i8 addrspace(1)* %obj
478 The pass would produce this IR:
482 define i8 addrspace(1)* @test1(i8 addrspace(1)* %obj)
483 gc "statepoint-example" {
484 %0 = call i32 (void ()*, i32, i32, ...)* @llvm.experimental.gc.statepoint.p0f_isVoidf(void ()* @foo, i32 0, i32 0, i32 5, i32 0, i32 -1, i32 0, i32 0, i32 0, i8 addrspace(1)* %obj)
485 %obj.relocated = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(i32 %0, i32 9, i32 9)
486 ret i8 addrspace(1)* %obj.relocated
489 In the above examples, the addrspace(1) marker on the pointers is the mechanism
490 that the ``statepoint-example`` GC strategy uses to distinguish references from
491 non references. Address space 1 is not globally reserved for this purpose.
493 This pass can be used an utility function by a language frontend that doesn't
494 want to manually reason about liveness, base pointers, or relocation when
495 constructing IR. As currently implemented, RewriteStatepointsForGC must be
496 run after SSA construction (i.e. mem2ref).
499 In practice, RewriteStatepointsForGC can be run much later in the pass
500 pipeline, after most optimization is already done. This helps to improve
501 the quality of the generated code when compiled with garbage collection support.
502 In the long run, this is the intended usage model. At this time, a few details
503 have yet to be worked out about the semantic model required to guarantee this
504 is always correct. As such, please use with caution and report bugs.
511 The pass PlaceSafepoints transforms a function's IR by replacing any call or
512 invoke instructions with appropriate ``gc.statepoint`` and ``gc.result`` pairs,
513 and inserting safepoint polls sufficient to ensure running code checks for a
514 safepoint request on a timely manner. This pass is expected to be run before
515 RewriteStatepointsForGC and thus does not produce full relocation sequences.
517 As an example, given input IR of the following:
521 define void @test() gc "statepoint-example" {
526 declare void @do_safepoint()
527 define void @gc.safepoint_poll() {
528 call void @do_safepoint()
533 This pass would produce the following IR:
537 define void @test() gc "statepoint-example" {
538 %safepoint_token = call i32 (void ()*, i32, i32, ...)* @llvm.experimental.gc.statepoint.p0f_isVoidf(void ()* @do_safepoint, i32 0, i32 0, i32 0)
539 %safepoint_token1 = call i32 (void ()*, i32, i32, ...)* @llvm.experimental.gc.statepoint.p0f_isVoidf(void ()* @foo, i32 0, i32 0, i32 0)
543 In this case, we've added an (unconditional) entry safepoint poll and converted the call into a ``gc.statepoint``. Note that despite appearances, the entry poll is not necessarily redundant. We'd have to know that ``foo`` and ``test`` were not mutually recursive for the poll to be redundant. In practice, you'd probably want to your poll definition to contain a conditional branch of some form.
546 At the moment, PlaceSafepoints can insert safepoint polls at method entry and
547 loop backedges locations. Extending this to work with return polls would be
548 straight forward if desired.
550 PlaceSafepoints includes a number of optimizations to avoid placing safepoint
551 polls at particular sites unless needed to ensure timely execution of a poll
552 under normal conditions. PlaceSafepoints does not attempt to ensure timely
553 execution of a poll under worst case conditions such as heavy system paging.
555 The implementation of a safepoint poll action is specified by looking up a
556 function of the name ``gc.safepoint_poll`` in the containing Module. The body
557 of this function is inserted at each poll site desired. While calls or invokes
558 inside this method are transformed to a ``gc.statepoints``, recursive poll
559 insertion is not performed.
561 If you are scheduling the RewriteStatepointsForGC pass late in the pass order,
562 you should probably schedule this pass immediately before it. The exception
563 would be if you need to preserve abstract frame information (e.g. for
564 deoptimization or introspection) at safepoints. In that case, ask on the
565 llvmdev mailing list for suggestions.
568 Bugs and Enhancements
569 =====================
571 Currently known bugs and enhancements under consideration can be
572 tracked by performing a `bugzilla search
573 <http://llvm.org/bugs/buglist.cgi?cmdtype=runnamed&namedcmd=Statepoint%20Bugs&list_id=64342>`_
574 for [Statepoint] in the summary field. When filing new bugs, please
575 use this tag so that interested parties see the newly filed bug. As
576 with most LLVM features, design discussions take place on `llvmdev
577 <http://lists.cs.uiuc.edu/mailman/listinfo/llvmdev>`_, and patches
578 should be sent to `llvm-commits
579 <http://lists.cs.uiuc.edu/mailman/listinfo/llvm-commits>`_ for review.