1 =====================================
2 Garbage Collection with LLVM
3 =====================================
11 This document covers how to integrate LLVM into a compiler for a language which
12 supports garbage collection. **Note that LLVM itself does not provide a
13 garbage collector.** You must provide your own.
18 First, you should pick a collector strategy. LLVM includes a number of built
19 in ones, but you can also implement a loadable plugin with a custom definition.
20 Note that the collector strategy is a description of how LLVM should generate
21 code such that it interacts with your collector and runtime, not a description
22 of the collector itself.
24 Next, mark your generated functions as using your chosen collector strategy.
25 From c++, you can call:
29 F.setGC(<collector description name>);
32 This will produce IR like the following fragment:
36 define void @foo() gc "<collector description name>" { ... }
39 When generating LLVM IR for your functions, you will need to:
41 * Use ``@llvm.gcread`` and/or ``@llvm.gcwrite`` in place of standard load and
42 store instructions. These intrinsics are used to represent load and store
43 barriers. If you collector does not require such barriers, you can skip
46 * Use the memory allocation routines provided by your garbage collector's
49 * If your collector requires them, generate type maps according to your
50 runtime's binary interface. LLVM is not involved in the process. In
51 particular, the LLVM type system is not suitable for conveying such
52 information though the compiler.
54 * Insert any coordination code required for interacting with your collector.
55 Many collectors require running application code to periodically check a
56 flag and conditionally call a runtime function. This is often referred to
59 You will need to identify roots (i.e. references to heap objects your collector
60 needs to know about) in your generated IR, so that LLVM can encode them into
61 your final stack maps. Depending on the collector strategy chosen, this is
62 accomplished by using either the ''@llvm.gcroot'' intrinsics or an
63 ''gc.statepoint'' relocation sequence.
65 Don't forget to create a root for each intermediate value that is generated when
66 evaluating an expression. In ``h(f(), g())``, the result of ``f()`` could
67 easily be collected if evaluating ``g()`` triggers a collection.
69 Finally, you need to link your runtime library with the generated program
70 executable (for a static compiler) or ensure the appropriate symbols are
71 available for the runtime linker (for a JIT compiler).
73 What is Garbage Collection?
74 ===========================
76 Garbage collection is a widely used technique that frees the programmer from
77 having to know the lifetimes of heap objects, making software easier to produce
78 and maintain. Many programming languages rely on garbage collection for
79 automatic memory management. There are two primary forms of garbage collection:
80 conservative and accurate.
82 Conservative garbage collection often does not require any special support from
83 either the language or the compiler: it can handle non-type-safe programming
84 languages (such as C/C++) and does not require any special information from the
85 compiler. The `Boehm collector
86 <http://www.hpl.hp.com/personal/Hans_Boehm/gc/>`__ is an example of a
87 state-of-the-art conservative collector.
89 Accurate garbage collection requires the ability to identify all pointers in the
90 program at run-time (which requires that the source-language be type-safe in
91 most cases). Identifying pointers at run-time requires compiler support to
92 locate all places that hold live pointer variables at run-time, including the
93 :ref:`processor stack and registers <gcroot>`.
95 Conservative garbage collection is attractive because it does not require any
96 special compiler support, but it does have problems. In particular, because the
97 conservative garbage collector cannot *know* that a particular word in the
98 machine is a pointer, it cannot move live objects in the heap (preventing the
99 use of compacting and generational GC algorithms) and it can occasionally suffer
100 from memory leaks due to integer values that happen to point to objects in the
101 program. In addition, some aggressive compiler transformations can break
102 conservative garbage collectors (though these seem rare in practice).
104 Accurate garbage collectors do not suffer from any of these problems, but they
105 can suffer from degraded scalar optimization of the program. In particular,
106 because the runtime must be able to identify and update all pointers active in
107 the program, some optimizations are less effective. In practice, however, the
108 locality and performance benefits of using aggressive garbage collection
109 techniques dominates any low-level losses.
111 This document describes the mechanisms and interfaces provided by LLVM to
112 support accurate garbage collection.
117 LLVM's intermediate representation provides :ref:`garbage collection intrinsics
118 <gc_intrinsics>` that offer support for a broad class of collector models. For
119 instance, the intrinsics permit:
121 * semi-space collectors
123 * mark-sweep collectors
125 * generational collectors
129 * incremental collectors
131 * concurrent collectors
133 * cooperative collectors
135 We hope that the primitive support built into the LLVM IR is sufficient to
136 support a broad class of garbage collected languages including Scheme, ML, Java,
137 C#, Perl, Python, Lua, Ruby, other scripting languages, and more.
139 However, LLVM does not itself provide a garbage collector --- this should be
140 part of your language's runtime library. LLVM provides a framework for compile
141 time :ref:`code generation plugins <plugin>`. The role of these plugins is to
142 generate code and data structures which conforms to the *binary interface*
143 specified by the *runtime library*. This is similar to the relationship between
144 LLVM and DWARF debugging info, for example. The difference primarily lies in
145 the lack of an established standard in the domain of garbage collection --- thus
148 The aspects of the binary interface with which LLVM's GC support is
151 * Creation of GC-safe points within code where collection is allowed to execute
154 * Computation of the stack map. For each safe point in the code, object
155 references within the stack frame must be identified so that the collector may
156 traverse and perhaps update them.
158 * Write barriers when storing object references to the heap. These are commonly
159 used to optimize incremental scans in generational collectors.
161 * Emission of read barriers when loading object references. These are useful
162 for interoperating with concurrent collectors.
164 There are additional areas that LLVM does not directly address:
166 * Registration of global roots with the runtime.
168 * Registration of stack map entries with the runtime.
170 * The functions used by the program to allocate memory, trigger a collection,
173 * Computation or compilation of type maps, or registration of them with the
174 runtime. These are used to crawl the heap for object references.
176 In general, LLVM's support for GC does not include features which can be
177 adequately addressed with other features of the IR and does not specify a
178 particular binary interface. On the plus side, this means that you should be
179 able to integrate LLVM with an existing runtime. On the other hand, it leaves a
180 lot of work for the developer of a novel language. However, it's easy to get
181 started quickly and scale up to a more sophisticated implementation as your
187 LLVM does not provide a garbage collector. You should be able to leverage any existing collector library that includes the following elements:
189 #. A memory allocator which exposes an allocation function your compiled
192 #. A binary format for the stack map. A stack map describes the location
193 of references at a safepoint and is used by precise collectors to identify
194 references within a stack frame on the machine stack. Note that collectors
195 which conservatively scan the stack don't require such a structure.
197 #. A stack crawler to discover functions on the call stack, and enumerate the
198 references listed in the stack map for each call site.
200 #. A mechanism for identifying references in global locations (e.g. global
203 #. If you collector requires them, an LLVM IR implementation of your collectors
204 load and store barriers. Note that since many collectors don't require
205 barriers at all, LLVM defaults to lowering such barriers to normal loads
206 and stores unless you arrange otherwise.
213 This section describes the garbage collection facilities provided by the
214 :doc:`LLVM intermediate representation <LangRef>`. The exact behavior of these
215 IR features is specified by the binary interface implemented by a :ref:`code
216 generation plugin <plugin>`, not by this document.
218 These facilities are limited to those strictly necessary; they are not intended
219 to be a complete interface to any garbage collector. A program will need to
220 interface with the GC library using the facilities provided by that program.
222 Specifying GC code generation: ``gc "..."``
223 -------------------------------------------
227 define ty @name(...) gc "name" { ...
229 The ``gc`` function attribute is used to specify the desired GC style to the
230 compiler. Its programmatic equivalent is the ``setGC`` method of ``Function``.
232 Setting ``gc "name"`` on a function triggers a search for a matching code
233 generation plugin "*name*"; it is that plugin which defines the exact nature of
234 the code generated to support GC. If none is found, the compiler will raise an
237 Specifying the GC style on a per-function basis allows LLVM to link together
238 programs that use different garbage collection algorithms (or none at all).
242 Identifying GC roots on the stack: ``llvm.gcroot``
243 --------------------------------------------------
247 void @llvm.gcroot(i8** %ptrloc, i8* %metadata)
249 The ``llvm.gcroot`` intrinsic is used to inform LLVM that a stack variable
250 references an object on the heap and is to be tracked for garbage collection.
251 The exact impact on generated code is specified by a :ref:`compiler plugin
252 <plugin>`. All calls to ``llvm.gcroot`` **must** reside inside the first basic
255 A compiler which uses mem2reg to raise imperative code using ``alloca`` into SSA
256 form need only add a call to ``@llvm.gcroot`` for those variables which a
257 pointers into the GC heap.
259 It is also important to mark intermediate values with ``llvm.gcroot``. For
260 example, consider ``h(f(), g())``. Beware leaking the result of ``f()`` in the
261 case that ``g()`` triggers a collection. Note, that stack variables must be
262 initialized and marked with ``llvm.gcroot`` in function's prologue.
264 The first argument **must** be a value referring to an alloca instruction or a
265 bitcast of an alloca. The second contains a pointer to metadata that should be
266 associated with the pointer, and **must** be a constant or global value
267 address. If your target collector uses tags, use a null pointer for metadata.
269 The ``%metadata`` argument can be used to avoid requiring heap objects to have
270 'isa' pointers or tag bits. [Appel89_, Goldberg91_, Tolmach94_] If specified,
271 its value will be tracked along with the location of the pointer in the stack
274 Consider the following fragment of Java code:
279 Object X; // A null-initialized reference to an object
283 This block (which may be located in the middle of a function or in a loop nest),
284 could be compiled to this LLVM code:
289 ;; In the entry block for the function, allocate the
290 ;; stack space for X, which is an LLVM pointer.
293 ;; Tell LLVM that the stack space is a stack root.
294 ;; Java has type-tags on objects, so we pass null as metadata.
295 %tmp = bitcast %Object** %X to i8**
296 call void @llvm.gcroot(i8** %tmp, i8* null)
299 ;; "CodeBlock" is the block corresponding to the start
300 ;; of the scope above.
302 ;; Java null-initializes pointers.
303 store %Object* null, %Object** %X
307 ;; As the pointer goes out of scope, store a null value into
308 ;; it, to indicate that the value is no longer live.
309 store %Object* null, %Object** %X
312 Reading and writing references in the heap
313 ------------------------------------------
315 Some collectors need to be informed when the mutator (the program that needs
316 garbage collection) either reads a pointer from or writes a pointer to a field
317 of a heap object. The code fragments inserted at these points are called *read
318 barriers* and *write barriers*, respectively. The amount of code that needs to
319 be executed is usually quite small and not on the critical path of any
320 computation, so the overall performance impact of the barrier is tolerable.
322 Barriers often require access to the *object pointer* rather than the *derived
323 pointer* (which is a pointer to the field within the object). Accordingly,
324 these intrinsics take both pointers as separate arguments for completeness. In
325 this snippet, ``%object`` is the object pointer, and ``%derived`` is the derived
331 %class.Array = type { %class.Object, i32, [0 x %class.Object*] }
334 ;; Load the object pointer from a gcroot.
335 %object = load %class.Array** %object_addr
337 ;; Compute the derived pointer.
338 %derived = getelementptr %object, i32 0, i32 2, i32 %n
340 LLVM does not enforce this relationship between the object and derived pointer
341 (although a :ref:`plugin <plugin>` might). However, it would be an unusual
342 collector that violated it.
344 The use of these intrinsics is naturally optional if the target GC does require
345 the corresponding barrier. Such a GC plugin will replace the intrinsic calls
346 with the corresponding ``load`` or ``store`` instruction if they are used.
348 Write barrier: ``llvm.gcwrite``
349 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
353 void @llvm.gcwrite(i8* %value, i8* %object, i8** %derived)
355 For write barriers, LLVM provides the ``llvm.gcwrite`` intrinsic function. It
356 has exactly the same semantics as a non-volatile ``store`` to the derived
357 pointer (the third argument). The exact code generated is specified by a
358 compiler :ref:`plugin <plugin>`.
360 Many important algorithms require write barriers, including generational and
361 concurrent collectors. Additionally, write barriers could be used to implement
364 Read barrier: ``llvm.gcread``
365 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
369 i8* @llvm.gcread(i8* %object, i8** %derived)
371 For read barriers, LLVM provides the ``llvm.gcread`` intrinsic function. It has
372 exactly the same semantics as a non-volatile ``load`` from the derived pointer
373 (the second argument). The exact code generated is specified by a
374 :ref:`compiler plugin <plugin>`.
376 Read barriers are needed by fewer algorithms than write barriers, and may have a
377 greater performance impact since pointer reads are more frequent than writes.
384 LLVM includes built in support for several varieties of garbage collectors.
387 ----------------------
389 To use this collector strategy, mark your functions with:
393 F.setGC("shadow-stack");
395 Unlike many GC algorithms which rely on a cooperative code generator to compile
396 stack maps, this algorithm carefully maintains a linked list of stack roots
397 [:ref:`Henderson2002 <henderson02>`]. This so-called "shadow stack" mirrors the
398 machine stack. Maintaining this data structure is slower than using a stack map
399 compiled into the executable as constant data, but has a significant portability
400 advantage because it requires no special support from the target code generator,
401 and does not require tricky platform-specific code to crawl the machine stack.
403 The tradeoff for this simplicity and portability is:
405 * High overhead per function call.
409 Still, it's an easy way to get started. After your compiler and runtime are up
410 and running, writing a :ref:`plugin <plugin>` will allow you to take advantage
411 of :ref:`more advanced GC features <collector-algos>` of LLVM in order to
415 The shadow stack doesn't imply a memory allocation algorithm. A semispace
416 collector or building atop ``malloc`` are great places to start, and can be
417 implemented with very little code.
419 When it comes time to collect, however, your runtime needs to traverse the stack
420 roots, and for this it needs to integrate with the shadow stack. Luckily, doing
421 so is very simple. (This code is heavily commented to help you understand the
422 data structure, but there are only 20 lines of meaningful code.)
426 /// @brief The map for a single function's stack frame. One of these is
427 /// compiled as constant data into the executable for each function.
429 /// Storage of metadata values is elided if the %metadata parameter to
430 /// @llvm.gcroot is null.
432 int32_t NumRoots; //< Number of roots in stack frame.
433 int32_t NumMeta; //< Number of metadata entries. May be < NumRoots.
434 const void *Meta[0]; //< Metadata for each root.
437 /// @brief A link in the dynamic shadow stack. One of these is embedded in
438 /// the stack frame of each function on the call stack.
440 StackEntry *Next; //< Link to next stack entry (the caller's).
441 const FrameMap *Map; //< Pointer to constant FrameMap.
442 void *Roots[0]; //< Stack roots (in-place array).
445 /// @brief The head of the singly-linked list of StackEntries. Functions push
446 /// and pop onto this in their prologue and epilogue.
448 /// Since there is only a global list, this technique is not threadsafe.
449 StackEntry *llvm_gc_root_chain;
451 /// @brief Calls Visitor(root, meta) for each GC root on the stack.
452 /// root and meta are exactly the values passed to
455 /// Visitor could be a function to recursively mark live objects. Or it
456 /// might copy them to another heap or generation.
458 /// @param Visitor A function to invoke for every GC root on the stack.
459 void visitGCRoots(void (*Visitor)(void **Root, const void *Meta)) {
460 for (StackEntry *R = llvm_gc_root_chain; R; R = R->Next) {
463 // For roots [0, NumMeta), the metadata pointer is in the FrameMap.
464 for (unsigned e = R->Map->NumMeta; i != e; ++i)
465 Visitor(&R->Roots[i], R->Map->Meta[i]);
467 // For roots [NumMeta, NumRoots), the metadata pointer is null.
468 for (unsigned e = R->Map->NumRoots; i != e; ++i)
469 Visitor(&R->Roots[i], NULL);
474 The 'Erlang' and 'Ocaml' GCs
475 -----------------------------
477 LLVM ships with two example collectors which leverage the ''gcroot''
478 mechanisms. To our knowledge, these are not actually used by any language
479 runtime, but they do provide a reasonable starting point for someone interested
480 in writing an ''gcroot' compatible GC plugin. In particular, these are the
481 only in tree examples of how to produce a custom binary stack map format using
482 a ''gcroot'' strategy.
484 As there names imply, the binary format produced is intended to model that
485 used by the Erlang and OCaml compilers respectively.
488 The Statepoint Example GC
489 -------------------------
493 F.setGC("statepoint-example");
495 This GC provides an example of how one might use the infrastructure provided
496 by ''gc.statepoint''.
502 If none of the built in GC strategy descriptions met your needs above, you will
503 need to define a custom GCStrategy and possibly, a custom LLVM pass to perform
504 lowering. Your best example of where to start defining a custom GCStrategy
505 would be to look at one of the built in strategies.
507 You may be able to structure this additional code as a loadable plugin library.
508 Loadable plugins are sufficient if all you need is to enable a different
509 combination of built in functionality, but if you need to provide a custom
510 lowering pass, you will need to build a patched version of LLVM. If you think
511 you need a patched build, please ask for advice on llvm-dev. There may be an
512 easy way we can extend the support to make it work for your use case without
513 requiring a custom build.
516 Implementing a collector plugin
517 -------------------------------
519 User code specifies which GC code generation to use with the ``gc`` function
520 attribute or, equivalently, with the ``setGC`` method of ``Function``.
522 To implement a GC plugin, it is necessary to subclass ``llvm::GCStrategy``,
523 which can be accomplished in a few lines of boilerplate code. LLVM's
524 infrastructure provides access to several important algorithms. For an
525 uncontroversial collector, all that remains may be to compile LLVM's computed
526 stack map to assembly code (using the binary representation expected by the
527 runtime library). This can be accomplished in about 100 lines of code.
529 This is not the appropriate place to implement a garbage collected heap or a
530 garbage collector itself. That code should exist in the language's runtime
531 library. The compiler plugin is responsible for generating code which conforms
532 to the binary interface defined by library, most essentially the :ref:`stack map
535 To subclass ``llvm::GCStrategy`` and register it with the compiler:
539 // lib/MyGC/MyGC.cpp - Example LLVM GC plugin
541 #include "llvm/CodeGen/GCStrategy.h"
542 #include "llvm/CodeGen/GCMetadata.h"
543 #include "llvm/Support/Compiler.h"
545 using namespace llvm;
548 class LLVM_LIBRARY_VISIBILITY MyGC : public GCStrategy {
553 GCRegistry::Add<MyGC>
554 X("mygc", "My bespoke garbage collector.");
557 This boilerplate collector does nothing. More specifically:
559 * ``llvm.gcread`` calls are replaced with the corresponding ``load``
562 * ``llvm.gcwrite`` calls are replaced with the corresponding ``store``
565 * No safe points are added to the code.
567 * The stack map is not compiled into the executable.
569 Using the LLVM makefiles, this code
570 can be compiled as a plugin using a simple makefile:
580 include $(LEVEL)/Makefile.common
582 Once the plugin is compiled, code using it may be compiled using ``llc
583 -load=MyGC.so`` (though MyGC.so may have some other platform-specific
589 define void @f() gc "mygc" {
593 $ llvm-as < sample.ll | llc -load=MyGC.so
595 It is also possible to statically link the collector plugin into tools, such as
596 a language-specific compiler front-end.
600 Overview of available features
601 ------------------------------
603 ``GCStrategy`` provides a range of features through which a plugin may do useful
604 work. Some of these are callbacks, some are algorithms that can be enabled,
605 disabled, or customized. This matrix summarizes the supported (and planned)
606 features and correlates them with the collection techniques which typically
609 .. |v| unicode:: 0x2714
612 .. |x| unicode:: 0x2718
615 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
616 | Algorithm | Done | Shadow | refcount | mark- | copying | incremental | threaded | concurrent |
617 | | | stack | | sweep | | | | |
618 +============+======+========+==========+=======+=========+=============+==========+============+
619 | stack map | |v| | | | |x| | |x| | |x| | |x| | |x| |
620 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
621 | initialize | |v| | |x| | |x| | |x| | |x| | |x| | |x| | |x| |
622 | roots | | | | | | | | |
623 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
624 | derived | NO | | | | | | **N**\* | **N**\* |
625 | pointers | | | | | | | | |
626 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
627 | **custom | |v| | | | | | | | |
628 | lowering** | | | | | | | | |
629 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
630 | *gcroot* | |v| | |x| | |x| | | | | | |
631 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
632 | *gcwrite* | |v| | | |x| | | | |x| | | |x| |
633 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
634 | *gcread* | |v| | | | | | | | |x| |
635 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
636 | **safe | | | | | | | | |
637 | points** | | | | | | | | |
638 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
639 | *in | |v| | | | |x| | |x| | |x| | |x| | |x| |
640 | calls* | | | | | | | | |
641 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
642 | *before | |v| | | | | | | |x| | |x| |
643 | calls* | | | | | | | | |
644 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
645 | *for | NO | | | | | | **N** | **N** |
646 | loops* | | | | | | | | |
647 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
648 | *before | |v| | | | | | | |x| | |x| |
649 | escape* | | | | | | | | |
650 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
651 | emit code | NO | | | | | | **N** | **N** |
652 | at safe | | | | | | | | |
653 | points | | | | | | | | |
654 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
655 | **output** | | | | | | | | |
656 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
657 | *assembly* | |v| | | | |x| | |x| | |x| | |x| | |x| |
658 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
659 | *JIT* | NO | | | **?** | **?** | **?** | **?** | **?** |
660 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
661 | *obj* | NO | | | **?** | **?** | **?** | **?** | **?** |
662 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
663 | live | NO | | | **?** | **?** | **?** | **?** | **?** |
664 | analysis | | | | | | | | |
665 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
666 | register | NO | | | **?** | **?** | **?** | **?** | **?** |
667 | map | | | | | | | | |
668 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
669 | \* Derived pointers only pose a hasard to copying collections. |
670 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
671 | **?** denotes a feature which could be utilized if available. |
672 +------------+------+--------+----------+-------+---------+-------------+----------+------------+
674 To be clear, the collection techniques above are defined as:
677 The mutator carefully maintains a linked list of stack roots.
680 The mutator maintains a reference count for each object and frees an object
681 when its count falls to zero.
684 When the heap is exhausted, the collector marks reachable objects starting
685 from the roots, then deallocates unreachable objects in a sweep phase.
688 As reachability analysis proceeds, the collector copies objects from one heap
689 area to another, compacting them in the process. Copying collectors enable
690 highly efficient "bump pointer" allocation and can improve locality of
694 (Including generational collectors.) Incremental collectors generally have all
695 the properties of a copying collector (regardless of whether the mature heap
696 is compacting), but bring the added complexity of requiring write barriers.
699 Denotes a multithreaded mutator; the collector must still stop the mutator
700 ("stop the world") before beginning reachability analysis. Stopping a
701 multithreaded mutator is a complicated problem. It generally requires highly
702 platform-specific code in the runtime, and the production of carefully
703 designed machine code at safe points.
706 In this technique, the mutator and the collector run concurrently, with the
707 goal of eliminating pause times. In a *cooperative* collector, the mutator
708 further aids with collection should a pause occur, allowing collection to take
709 advantage of multiprocessor hosts. The "stop the world" problem of threaded
710 collectors is generally still present to a limited extent. Sophisticated
711 marking algorithms are necessary. Read barriers may be necessary.
713 As the matrix indicates, LLVM's garbage collection infrastructure is already
714 suitable for a wide variety of collectors, but does not currently extend to
715 multithreaded programs. This will be added in the future as there is
723 LLVM automatically computes a stack map. One of the most important features
724 of a ``GCStrategy`` is to compile this information into the executable in
725 the binary representation expected by the runtime library.
727 The stack map consists of the location and identity of each GC root in the
728 each function in the module. For each root:
730 * ``RootNum``: The index of the root.
732 * ``StackOffset``: The offset of the object relative to the frame pointer.
734 * ``RootMetadata``: The value passed as the ``%metadata`` parameter to the
735 ``@llvm.gcroot`` intrinsic.
737 Also, for the function as a whole:
739 * ``getFrameSize()``: The overall size of the function's initial stack frame,
740 not accounting for any dynamic allocation.
742 * ``roots_size()``: The count of roots in the function.
744 To access the stack map, use ``GCFunctionMetadata::roots_begin()`` and
745 -``end()`` from the :ref:`GCMetadataPrinter <assembly>`:
749 for (iterator I = begin(), E = end(); I != E; ++I) {
750 GCFunctionInfo *FI = *I;
751 unsigned FrameSize = FI->getFrameSize();
752 size_t RootCount = FI->roots_size();
754 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin(),
755 RE = FI->roots_end();
757 int RootNum = RI->Num;
758 int RootStackOffset = RI->StackOffset;
759 Constant *RootMetadata = RI->Metadata;
763 If the ``llvm.gcroot`` intrinsic is eliminated before code generation by a
764 custom lowering pass, LLVM will compute an empty stack map. This may be useful
765 for collector plugins which implement reference counting or a shadow stack.
769 Initializing roots to null: ``InitRoots``
770 -----------------------------------------
778 When set, LLVM will automatically initialize each root to ``null`` upon entry to
779 the function. This prevents the GC's sweep phase from visiting uninitialized
780 pointers, which will almost certainly cause it to crash. This initialization
781 occurs before custom lowering, so the two may be used together.
783 Since LLVM does not yet compute liveness information, there is no means of
784 distinguishing an uninitialized stack root from an initialized one. Therefore,
785 this feature should be used by all GC plugins. It is enabled by default.
787 Custom lowering of intrinsics: ``CustomRoots``, ``CustomReadBarriers``, and ``CustomWriteBarriers``
788 ---------------------------------------------------------------------------------------------------
790 For GCs which use barriers or unusual treatment of stack roots, these
791 flags allow the collector to perform arbitrary transformations of the
796 class MyGC : public GCStrategy {
800 CustomReadBarriers = true;
801 CustomWriteBarriers = true;
805 If any of these flags are set, LLVM suppresses its default lowering for
806 the corresponding intrinsics. Instead, you must provide a custom Pass
807 which lowers the intrinsics as desired. If you have opted in to custom
808 lowering of a particular intrinsic your pass **must** eliminate all
809 instances of the corresponding intrinsic in functions which opt in to
810 your GC. The best example of such a pass is the ShadowStackGC and it's
811 ShadowStackGCLowering pass.
813 There is currently no way to register such a custom lowering pass
814 without building a custom copy of LLVM.
818 Generating safe points: ``NeededSafePoints``
819 --------------------------------------------
821 LLVM can compute four kinds of safe points:
826 /// PointKind - The type of a collector-safe point.
829 Loop, //< Instr is a loop (backwards branch).
830 Return, //< Instr is a return instruction.
831 PreCall, //< Instr is a call instruction.
832 PostCall //< Instr is the return address of a call.
836 A collector can request any combination of the four by setting the
837 ``NeededSafePoints`` mask:
842 NeededSafePoints = 1 << GC::Loop
848 It can then use the following routines to access safe points.
852 for (iterator I = begin(), E = end(); I != E; ++I) {
853 GCFunctionInfo *MD = *I;
854 size_t PointCount = MD->size();
856 for (GCFunctionInfo::iterator PI = MD->begin(),
857 PE = MD->end(); PI != PE; ++PI) {
858 GC::PointKind PointKind = PI->Kind;
859 unsigned PointNum = PI->Num;
863 Almost every collector requires ``PostCall`` safe points, since these correspond
864 to the moments when the function is suspended during a call to a subroutine.
866 Threaded programs generally require ``Loop`` safe points to guarantee that the
867 application will reach a safe point within a bounded amount of time, even if it
868 is executing a long-running loop which contains no function calls.
870 Threaded collectors may also require ``Return`` and ``PreCall`` safe points to
871 implement "stop the world" techniques using self-modifying code, where it is
872 important that the program not exit the function without reaching a safe point
873 (because only the topmost function has been patched).
877 Emitting assembly code: ``GCMetadataPrinter``
878 ---------------------------------------------
880 LLVM allows a plugin to print arbitrary assembly code before and after the rest
881 of a module's assembly code. At the end of the module, the GC can compile the
882 LLVM stack map into assembly code. (At the beginning, this information is not
885 Since AsmWriter and CodeGen are separate components of LLVM, a separate abstract
886 base class and registry is provided for printing assembly code, the
887 ``GCMetadaPrinter`` and ``GCMetadataPrinterRegistry``. The AsmWriter will look
888 for such a subclass if the ``GCStrategy`` sets ``UsesMetadata``:
896 This separation allows JIT-only clients to be smaller.
898 Note that LLVM does not currently have analogous APIs to support code generation
899 in the JIT, nor using the object writers.
903 // lib/MyGC/MyGCPrinter.cpp - Example LLVM GC printer
905 #include "llvm/CodeGen/GCMetadataPrinter.h"
906 #include "llvm/Support/Compiler.h"
908 using namespace llvm;
911 class LLVM_LIBRARY_VISIBILITY MyGCPrinter : public GCMetadataPrinter {
913 virtual void beginAssembly(AsmPrinter &AP);
915 virtual void finishAssembly(AsmPrinter &AP);
918 GCMetadataPrinterRegistry::Add<MyGCPrinter>
919 X("mygc", "My bespoke garbage collector.");
922 The collector should use ``AsmPrinter`` to print portable assembly code. The
923 collector itself contains the stack map for the entire module, and may access
924 the ``GCFunctionInfo`` using its own ``begin()`` and ``end()`` methods. Here's
929 #include "llvm/CodeGen/AsmPrinter.h"
930 #include "llvm/IR/Function.h"
931 #include "llvm/IR/DataLayout.h"
932 #include "llvm/Target/TargetAsmInfo.h"
933 #include "llvm/Target/TargetMachine.h"
935 void MyGCPrinter::beginAssembly(AsmPrinter &AP) {
939 void MyGCPrinter::finishAssembly(AsmPrinter &AP) {
940 MCStreamer &OS = AP.OutStreamer;
941 unsigned IntPtrSize = AP.TM.getSubtargetImpl()->getDataLayout()->getPointerSize();
943 // Put this in the data section.
944 OS.SwitchSection(AP.getObjFileLowering().getDataSection());
946 // For each function...
947 for (iterator FI = begin(), FE = end(); FI != FE; ++FI) {
948 GCFunctionInfo &MD = **FI;
950 // A compact GC layout. Emit this data structure:
953 // int32_t PointCount;
954 // void *SafePointAddress[PointCount];
955 // int32_t StackFrameSize; // in words
956 // int32_t StackArity;
957 // int32_t LiveCount;
958 // int32_t LiveOffsets[LiveCount];
959 // } __gcmap_<FUNCTIONNAME>;
961 // Align to address width.
962 AP.EmitAlignment(IntPtrSize == 4 ? 2 : 3);
965 OS.AddComment("safe point count");
966 AP.EmitInt32(MD.size());
968 // And each safe point...
969 for (GCFunctionInfo::iterator PI = MD.begin(),
970 PE = MD.end(); PI != PE; ++PI) {
971 // Emit the address of the safe point.
972 OS.AddComment("safe point address");
973 MCSymbol *Label = PI->Label;
974 AP.EmitLabelPlusOffset(Label/*Hi*/, 0/*Offset*/, 4/*Size*/);
977 // Stack information never change in safe points! Only print info from the
979 GCFunctionInfo::iterator PI = MD.begin();
981 // Emit the stack frame size.
982 OS.AddComment("stack frame size (in words)");
983 AP.EmitInt32(MD.getFrameSize() / IntPtrSize);
985 // Emit stack arity, i.e. the number of stacked arguments.
986 unsigned RegisteredArgs = IntPtrSize == 4 ? 5 : 6;
987 unsigned StackArity = MD.getFunction().arg_size() > RegisteredArgs ?
988 MD.getFunction().arg_size() - RegisteredArgs : 0;
989 OS.AddComment("stack arity");
990 AP.EmitInt32(StackArity);
992 // Emit the number of live roots in the function.
993 OS.AddComment("live root count");
994 AP.EmitInt32(MD.live_size(PI));
996 // And for each live root...
997 for (GCFunctionInfo::live_iterator LI = MD.live_begin(PI),
998 LE = MD.live_end(PI);
1000 // Emit live root's offset within the stack frame.
1001 OS.AddComment("stack index (offset / wordsize)");
1002 AP.EmitInt32(LI->StackOffset);
1012 [Appel89] Runtime Tags Aren't Necessary. Andrew W. Appel. Lisp and Symbolic
1013 Computation 19(7):703-705, July 1989.
1017 [Goldberg91] Tag-free garbage collection for strongly typed programming
1018 languages. Benjamin Goldberg. ACM SIGPLAN PLDI'91.
1022 [Tolmach94] Tag-free garbage collection using explicit type parameters. Andrew
1023 Tolmach. Proceedings of the 1994 ACM conference on LISP and functional
1028 [Henderson2002] `Accurate Garbage Collection in an Uncooperative Environment
1029 <http://citeseer.ist.psu.edu/henderson02accurate.html>`__