blob: 5d1588a7fe41e45efa4e62de2c5ecb5f01888926 [file] [log] [blame]
Sean Silva18dc5382012-12-09 15:52:47 +00001=====================================
Philip Reamese78cf552015-02-24 19:44:46 +00002Garbage Collection with LLVM
Sean Silva18dc5382012-12-09 15:52:47 +00003=====================================
4
5.. contents::
6 :local:
7
Philip Reames38263192015-02-24 23:34:24 +00008Abstract
9========
Sean Silva18dc5382012-12-09 15:52:47 +000010
Philip Reamese78cf552015-02-24 19:44:46 +000011This document covers how to integrate LLVM into a compiler for a language which
12supports garbage collection. **Note that LLVM itself does not provide a
13garbage collector.** You must provide your own.
14
Philip Reames03f38362015-02-24 23:12:27 +000015Quick Start
16============
Philip Reamese78cf552015-02-24 19:44:46 +000017
Philip Reames03f38362015-02-24 23:12:27 +000018First, you should pick a collector strategy. LLVM includes a number of built
19in ones, but you can also implement a loadable plugin with a custom definition.
20Note that the collector strategy is a description of how LLVM should generate
21code such that it interacts with your collector and runtime, not a description
22of the collector itself.
Philip Reamese78cf552015-02-24 19:44:46 +000023
Philip Reames03f38362015-02-24 23:12:27 +000024Next, mark your generated functions as using your chosen collector strategy.
25From c++, you can call:
Philip Reamese78cf552015-02-24 19:44:46 +000026
27.. code-block:: c++
28
29 F.setGC(<collector description name>);
30
Philip Reamese78cf552015-02-24 19:44:46 +000031
Philip Reames03f38362015-02-24 23:12:27 +000032This will produce IR like the following fragment:
Philip Reamese78cf552015-02-24 19:44:46 +000033
Philip Reames03f38362015-02-24 23:12:27 +000034.. code-block:: llvm
Philip Reamese78cf552015-02-24 19:44:46 +000035
Philip Reames03f38362015-02-24 23:12:27 +000036 define void @foo() gc "<collector description name>" { ... }
Philip Reamese78cf552015-02-24 19:44:46 +000037
38
Philip Reames03f38362015-02-24 23:12:27 +000039When generating LLVM IR for your functions, you will need to:
Philip Reamese78cf552015-02-24 19:44:46 +000040
Philip Reames03f38362015-02-24 23:12:27 +000041* 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
44 this step.
Philip Reamese78cf552015-02-24 19:44:46 +000045
Philip Reames03f38362015-02-24 23:12:27 +000046* Use the memory allocation routines provided by your garbage collector's
47 runtime library.
48
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.
53
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
57 as a safepoint poll.
58
59You will need to identify roots (i.e. references to heap objects your collector
60needs to know about) in your generated IR, so that LLVM can encode them into
61your final stack maps. Depending on the collector strategy chosen, this is
Philip Reamesc609a592015-02-25 00:22:07 +000062accomplished by using either the ``@llvm.gcroot`` intrinsics or an
63``gc.statepoint`` relocation sequence.
Philip Reames03f38362015-02-24 23:12:27 +000064
65Don't forget to create a root for each intermediate value that is generated when
66evaluating an expression. In ``h(f(), g())``, the result of ``f()`` could
67easily be collected if evaluating ``g()`` triggers a collection.
68
69Finally, you need to link your runtime library with the generated program
70executable (for a static compiler) or ensure the appropriate symbols are
71available for the runtime linker (for a JIT compiler).
Philip Reamese78cf552015-02-24 19:44:46 +000072
Philip Reames38263192015-02-24 23:34:24 +000073
74Introduction
75============
76
Philip Reamese78cf552015-02-24 19:44:46 +000077What is Garbage Collection?
Philip Reames38263192015-02-24 23:34:24 +000078---------------------------
Philip Reamese78cf552015-02-24 19:44:46 +000079
Sean Silva18dc5382012-12-09 15:52:47 +000080Garbage collection is a widely used technique that frees the programmer from
81having to know the lifetimes of heap objects, making software easier to produce
82and maintain. Many programming languages rely on garbage collection for
83automatic memory management. There are two primary forms of garbage collection:
84conservative and accurate.
85
86Conservative garbage collection often does not require any special support from
87either the language or the compiler: it can handle non-type-safe programming
88languages (such as C/C++) and does not require any special information from the
89compiler. The `Boehm collector
90<http://www.hpl.hp.com/personal/Hans_Boehm/gc/>`__ is an example of a
91state-of-the-art conservative collector.
92
93Accurate garbage collection requires the ability to identify all pointers in the
94program at run-time (which requires that the source-language be type-safe in
95most cases). Identifying pointers at run-time requires compiler support to
96locate all places that hold live pointer variables at run-time, including the
97:ref:`processor stack and registers <gcroot>`.
98
99Conservative garbage collection is attractive because it does not require any
100special compiler support, but it does have problems. In particular, because the
101conservative garbage collector cannot *know* that a particular word in the
102machine is a pointer, it cannot move live objects in the heap (preventing the
103use of compacting and generational GC algorithms) and it can occasionally suffer
104from memory leaks due to integer values that happen to point to objects in the
105program. In addition, some aggressive compiler transformations can break
106conservative garbage collectors (though these seem rare in practice).
107
108Accurate garbage collectors do not suffer from any of these problems, but they
109can suffer from degraded scalar optimization of the program. In particular,
110because the runtime must be able to identify and update all pointers active in
111the program, some optimizations are less effective. In practice, however, the
112locality and performance benefits of using aggressive garbage collection
113techniques dominates any low-level losses.
114
115This document describes the mechanisms and interfaces provided by LLVM to
116support accurate garbage collection.
117
Sean Silva18dc5382012-12-09 15:52:47 +0000118Goals and non-goals
119-------------------
120
121LLVM's intermediate representation provides :ref:`garbage collection intrinsics
122<gc_intrinsics>` that offer support for a broad class of collector models. For
123instance, the intrinsics permit:
124
125* semi-space collectors
126
127* mark-sweep collectors
128
129* generational collectors
130
Sean Silva18dc5382012-12-09 15:52:47 +0000131* incremental collectors
132
133* concurrent collectors
134
135* cooperative collectors
136
Philip Reames38263192015-02-24 23:34:24 +0000137* reference counting
Sean Silva18dc5382012-12-09 15:52:47 +0000138
Philip Reames38263192015-02-24 23:34:24 +0000139We hope that the support built into the LLVM IR is sufficient to support a
140broad class of garbage collected languages including Scheme, ML, Java, C#,
141Perl, Python, Lua, Ruby, other scripting languages, and more.
142
143Note that LLVM **does not itself provide a garbage collector** --- this should
144be part of your language's runtime library. LLVM provides a framework for
145describing the garbage collectors requirements to the compiler. In particular,
146LLVM provides support for generating stack maps at call sites, polling for a
147safepoint, and emitting load and store barriers. You can also extend LLVM -
148possibly through a loadable :ref:`code generation plugins <plugin>` - to
Sean Silva18dc5382012-12-09 15:52:47 +0000149generate code and data structures which conforms to the *binary interface*
150specified by the *runtime library*. This is similar to the relationship between
151LLVM and DWARF debugging info, for example. The difference primarily lies in
152the lack of an established standard in the domain of garbage collection --- thus
Philip Reames38263192015-02-24 23:34:24 +0000153the need for a flexible extension mechanism.
Sean Silva18dc5382012-12-09 15:52:47 +0000154
155The aspects of the binary interface with which LLVM's GC support is
156concerned are:
157
Philip Reames38263192015-02-24 23:34:24 +0000158* Creation of GC safepoints within code where collection is allowed to execute
Sean Silva18dc5382012-12-09 15:52:47 +0000159 safely.
160
161* Computation of the stack map. For each safe point in the code, object
162 references within the stack frame must be identified so that the collector may
163 traverse and perhaps update them.
164
165* Write barriers when storing object references to the heap. These are commonly
166 used to optimize incremental scans in generational collectors.
167
168* Emission of read barriers when loading object references. These are useful
169 for interoperating with concurrent collectors.
170
171There are additional areas that LLVM does not directly address:
172
173* Registration of global roots with the runtime.
174
175* Registration of stack map entries with the runtime.
176
177* The functions used by the program to allocate memory, trigger a collection,
178 etc.
179
180* Computation or compilation of type maps, or registration of them with the
181 runtime. These are used to crawl the heap for object references.
182
183In general, LLVM's support for GC does not include features which can be
184adequately addressed with other features of the IR and does not specify a
185particular binary interface. On the plus side, this means that you should be
Philip Reames38263192015-02-24 23:34:24 +0000186able to integrate LLVM with an existing runtime. On the other hand, it can
187have the effect of leaving a lot of work for the developer of a novel
188language. We try to mitigate this by providing built in collector strategy
189descriptions that can work with many common collector designs and easy
190extension points. If you don't already have a specific binary interface
191you need to support, we recommend trying to use one of these built in collector
192strategies.
Philip Reames03f38362015-02-24 23:12:27 +0000193
Sean Silva18dc5382012-12-09 15:52:47 +0000194.. _gc_intrinsics:
195
Philip Reames03f38362015-02-24 23:12:27 +0000196LLVM IR Features
197================
Sean Silva18dc5382012-12-09 15:52:47 +0000198
199This section describes the garbage collection facilities provided by the
200:doc:`LLVM intermediate representation <LangRef>`. The exact behavior of these
Philip Reames50e9aed2015-02-24 23:51:37 +0000201IR features is specified by the selected :ref:`GC strategy description
202<plugin>`.
Sean Silva18dc5382012-12-09 15:52:47 +0000203
Sean Silva18dc5382012-12-09 15:52:47 +0000204Specifying GC code generation: ``gc "..."``
205-------------------------------------------
206
207.. code-block:: llvm
208
Philip Reames50e9aed2015-02-24 23:51:37 +0000209 define <returntype> @name(...) gc "name" { ... }
Sean Silva18dc5382012-12-09 15:52:47 +0000210
Philip Reames50e9aed2015-02-24 23:51:37 +0000211The ``gc`` function attribute is used to specify the desired GC strategy to the
Sean Silva18dc5382012-12-09 15:52:47 +0000212compiler. Its programmatic equivalent is the ``setGC`` method of ``Function``.
213
Philip Reames50e9aed2015-02-24 23:51:37 +0000214Setting ``gc "name"`` on a function triggers a search for a matching subclass
215of GCStrategy. Some collector strategies are built in. You can add others
216using either the loadable plugin mechanism, or by patching your copy of LLVM.
217It is the selected GC strategy which defines the exact nature of the code
218generated to support GC. If none is found, the compiler will raise an error.
Sean Silva18dc5382012-12-09 15:52:47 +0000219
220Specifying the GC style on a per-function basis allows LLVM to link together
221programs that use different garbage collection algorithms (or none at all).
222
223.. _gcroot:
224
Philip Reamese0dd0f22015-02-25 00:18:04 +0000225Identifying GC roots on the stack
226----------------------------------
227
228LLVM currently supports two different mechanisms for describing references in
229compiled code at safepoints. ``llvm.gcroot`` is the older mechanism;
230``gc.statepoint`` has been added more recently. At the moment, you can choose
231either implementation (on a per :ref:`GC strategy <plugin>` basis). Longer
232term, we will probably either migrate away from ``llvm.gcroot`` entirely, or
233substantially merge their implementations. Note that most new development
234work is focused on ``gc.statepoint``.
235
236Using ``gc.statepoint``
237^^^^^^^^^^^^^^^^^^^^^^^^
238:doc:`This page <Statepoints>` contains detailed documentation for
239``gc.statepoint``.
240
241Using ``llvm.gcwrite``
242^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Sean Silva18dc5382012-12-09 15:52:47 +0000243
244.. code-block:: llvm
245
246 void @llvm.gcroot(i8** %ptrloc, i8* %metadata)
247
248The ``llvm.gcroot`` intrinsic is used to inform LLVM that a stack variable
249references an object on the heap and is to be tracked for garbage collection.
Philip Reames09b52fd2015-02-25 23:07:34 +0000250The exact impact on generated code is specified by the Function's selected
251:ref:`GC strategy <plugin>`. All calls to ``llvm.gcroot`` **must** reside
252inside the first basic block.
Sean Silva18dc5382012-12-09 15:52:47 +0000253
Philip Reamese0dd0f22015-02-25 00:18:04 +0000254The first argument **must** be a value referring to an alloca instruction or a
255bitcast of an alloca. The second contains a pointer to metadata that should be
256associated with the pointer, and **must** be a constant or global value
257address. If your target collector uses tags, use a null pointer for metadata.
258
259A compiler which performs manual SSA construction **must** ensure that SSA
260values representing GC references are stored in to the alloca passed to the
261respective ``gcroot`` before every call site and reloaded after every call.
262A compiler which uses mem2reg to raise imperative code using ``alloca`` into
263SSA form need only add a call to ``@llvm.gcroot`` for those variables which
264are pointers into the GC heap.
Sean Silva18dc5382012-12-09 15:52:47 +0000265
266It is also important to mark intermediate values with ``llvm.gcroot``. For
267example, consider ``h(f(), g())``. Beware leaking the result of ``f()`` in the
268case that ``g()`` triggers a collection. Note, that stack variables must be
269initialized and marked with ``llvm.gcroot`` in function's prologue.
270
Sean Silva18dc5382012-12-09 15:52:47 +0000271The ``%metadata`` argument can be used to avoid requiring heap objects to have
272'isa' pointers or tag bits. [Appel89_, Goldberg91_, Tolmach94_] If specified,
273its value will be tracked along with the location of the pointer in the stack
274frame.
275
276Consider the following fragment of Java code:
277
278.. code-block:: java
279
280 {
281 Object X; // A null-initialized reference to an object
282 ...
283 }
284
285This block (which may be located in the middle of a function or in a loop nest),
286could be compiled to this LLVM code:
287
288.. code-block:: llvm
289
290 Entry:
291 ;; In the entry block for the function, allocate the
292 ;; stack space for X, which is an LLVM pointer.
293 %X = alloca %Object*
294
295 ;; Tell LLVM that the stack space is a stack root.
296 ;; Java has type-tags on objects, so we pass null as metadata.
297 %tmp = bitcast %Object** %X to i8**
298 call void @llvm.gcroot(i8** %tmp, i8* null)
299 ...
300
301 ;; "CodeBlock" is the block corresponding to the start
302 ;; of the scope above.
303 CodeBlock:
304 ;; Java null-initializes pointers.
305 store %Object* null, %Object** %X
306
307 ...
308
309 ;; As the pointer goes out of scope, store a null value into
310 ;; it, to indicate that the value is no longer live.
311 store %Object* null, %Object** %X
312 ...
313
Sean Silva18dc5382012-12-09 15:52:47 +0000314Reading and writing references in the heap
315------------------------------------------
316
317Some collectors need to be informed when the mutator (the program that needs
318garbage collection) either reads a pointer from or writes a pointer to a field
319of a heap object. The code fragments inserted at these points are called *read
320barriers* and *write barriers*, respectively. The amount of code that needs to
321be executed is usually quite small and not on the critical path of any
322computation, so the overall performance impact of the barrier is tolerable.
323
324Barriers often require access to the *object pointer* rather than the *derived
325pointer* (which is a pointer to the field within the object). Accordingly,
326these intrinsics take both pointers as separate arguments for completeness. In
327this snippet, ``%object`` is the object pointer, and ``%derived`` is the derived
328pointer:
329
330.. code-block:: llvm
331
332 ;; An array type.
333 %class.Array = type { %class.Object, i32, [0 x %class.Object*] }
334 ...
335
336 ;; Load the object pointer from a gcroot.
337 %object = load %class.Array** %object_addr
338
339 ;; Compute the derived pointer.
340 %derived = getelementptr %object, i32 0, i32 2, i32 %n
341
342LLVM does not enforce this relationship between the object and derived pointer
Philip Reames50e9aed2015-02-24 23:51:37 +0000343(although a particular :ref:`collector strategy <plugin>` might). However, it
344would be an unusual collector that violated it.
Sean Silva18dc5382012-12-09 15:52:47 +0000345
Philip Reames50e9aed2015-02-24 23:51:37 +0000346The use of these intrinsics is naturally optional if the target GC does not
347require the corresponding barrier. The GC strategy used with such a collector
348should replace the intrinsic calls with the corresponding ``load`` or
349``store`` instruction if they are used.
350
351One known deficiency with the current design is that the barrier intrinsics do
352not include the size or alignment of the underlying operation performed. It is
353currently assumed that the operation is of pointer size and the alignment is
354assumed to be the target machine's default alignment.
Sean Silva18dc5382012-12-09 15:52:47 +0000355
Sean Silva18dc5382012-12-09 15:52:47 +0000356Write barrier: ``llvm.gcwrite``
357^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
358
359.. code-block:: llvm
360
361 void @llvm.gcwrite(i8* %value, i8* %object, i8** %derived)
362
363For write barriers, LLVM provides the ``llvm.gcwrite`` intrinsic function. It
364has exactly the same semantics as a non-volatile ``store`` to the derived
Philip Reames50e9aed2015-02-24 23:51:37 +0000365pointer (the third argument). The exact code generated is specified by the
366Function's selected :ref:`GC strategy <plugin>`.
Sean Silva18dc5382012-12-09 15:52:47 +0000367
368Many important algorithms require write barriers, including generational and
369concurrent collectors. Additionally, write barriers could be used to implement
370reference counting.
371
Sean Silva18dc5382012-12-09 15:52:47 +0000372Read barrier: ``llvm.gcread``
373^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
374
375.. code-block:: llvm
376
377 i8* @llvm.gcread(i8* %object, i8** %derived)
378
379For read barriers, LLVM provides the ``llvm.gcread`` intrinsic function. It has
380exactly the same semantics as a non-volatile ``load`` from the derived pointer
Philip Reames50e9aed2015-02-24 23:51:37 +0000381(the second argument). The exact code generated is specified by the Function's
382selected :ref:`GC strategy <plugin>`.
Sean Silva18dc5382012-12-09 15:52:47 +0000383
384Read barriers are needed by fewer algorithms than write barriers, and may have a
385greater performance impact since pointer reads are more frequent than writes.
386
387.. _plugin:
388
Philip Reamese6625502015-02-25 23:22:43 +0000389Built In GC Strategies
390======================
Philip Reamese78cf552015-02-24 19:44:46 +0000391
392LLVM includes built in support for several varieties of garbage collectors.
393
394The Shadow Stack GC
395----------------------
396
397To use this collector strategy, mark your functions with:
398
399.. code-block:: c++
400
401 F.setGC("shadow-stack");
402
403Unlike many GC algorithms which rely on a cooperative code generator to compile
404stack maps, this algorithm carefully maintains a linked list of stack roots
405[:ref:`Henderson2002 <henderson02>`]. This so-called "shadow stack" mirrors the
406machine stack. Maintaining this data structure is slower than using a stack map
407compiled into the executable as constant data, but has a significant portability
408advantage because it requires no special support from the target code generator,
409and does not require tricky platform-specific code to crawl the machine stack.
410
411The tradeoff for this simplicity and portability is:
412
413* High overhead per function call.
414
415* Not thread-safe.
416
417Still, it's an easy way to get started. After your compiler and runtime are up
418and running, writing a :ref:`plugin <plugin>` will allow you to take advantage
419of :ref:`more advanced GC features <collector-algos>` of LLVM in order to
420improve performance.
421
Philip Reames03f38362015-02-24 23:12:27 +0000422
423The shadow stack doesn't imply a memory allocation algorithm. A semispace
424collector or building atop ``malloc`` are great places to start, and can be
425implemented with very little code.
426
427When it comes time to collect, however, your runtime needs to traverse the stack
428roots, and for this it needs to integrate with the shadow stack. Luckily, doing
429so is very simple. (This code is heavily commented to help you understand the
430data structure, but there are only 20 lines of meaningful code.)
431
432.. code-block:: c++
433
434 /// @brief The map for a single function's stack frame. One of these is
435 /// compiled as constant data into the executable for each function.
436 ///
437 /// Storage of metadata values is elided if the %metadata parameter to
438 /// @llvm.gcroot is null.
439 struct FrameMap {
440 int32_t NumRoots; //< Number of roots in stack frame.
441 int32_t NumMeta; //< Number of metadata entries. May be < NumRoots.
442 const void *Meta[0]; //< Metadata for each root.
443 };
444
445 /// @brief A link in the dynamic shadow stack. One of these is embedded in
446 /// the stack frame of each function on the call stack.
447 struct StackEntry {
448 StackEntry *Next; //< Link to next stack entry (the caller's).
449 const FrameMap *Map; //< Pointer to constant FrameMap.
450 void *Roots[0]; //< Stack roots (in-place array).
451 };
452
453 /// @brief The head of the singly-linked list of StackEntries. Functions push
454 /// and pop onto this in their prologue and epilogue.
455 ///
456 /// Since there is only a global list, this technique is not threadsafe.
457 StackEntry *llvm_gc_root_chain;
458
459 /// @brief Calls Visitor(root, meta) for each GC root on the stack.
460 /// root and meta are exactly the values passed to
461 /// @llvm.gcroot.
462 ///
463 /// Visitor could be a function to recursively mark live objects. Or it
464 /// might copy them to another heap or generation.
465 ///
466 /// @param Visitor A function to invoke for every GC root on the stack.
467 void visitGCRoots(void (*Visitor)(void **Root, const void *Meta)) {
468 for (StackEntry *R = llvm_gc_root_chain; R; R = R->Next) {
469 unsigned i = 0;
470
471 // For roots [0, NumMeta), the metadata pointer is in the FrameMap.
472 for (unsigned e = R->Map->NumMeta; i != e; ++i)
473 Visitor(&R->Roots[i], R->Map->Meta[i]);
474
475 // For roots [NumMeta, NumRoots), the metadata pointer is null.
476 for (unsigned e = R->Map->NumRoots; i != e; ++i)
477 Visitor(&R->Roots[i], NULL);
478 }
479 }
480
481
Philip Reamese78cf552015-02-24 19:44:46 +0000482The 'Erlang' and 'Ocaml' GCs
483-----------------------------
484
Philip Reamesc609a592015-02-25 00:22:07 +0000485LLVM ships with two example collectors which leverage the ``gcroot``
Philip Reamese78cf552015-02-24 19:44:46 +0000486mechanisms. To our knowledge, these are not actually used by any language
487runtime, but they do provide a reasonable starting point for someone interested
Philip Reamesc609a592015-02-25 00:22:07 +0000488in writing an ``gcroot`` compatible GC plugin. In particular, these are the
Philip Reamese78cf552015-02-24 19:44:46 +0000489only in tree examples of how to produce a custom binary stack map format using
Philip Reamesc609a592015-02-25 00:22:07 +0000490a ``gcroot`` strategy.
Philip Reamese78cf552015-02-24 19:44:46 +0000491
492As there names imply, the binary format produced is intended to model that
493used by the Erlang and OCaml compilers respectively.
494
495
496The Statepoint Example GC
497-------------------------
498
499.. code-block:: c++
500
501 F.setGC("statepoint-example");
502
503This GC provides an example of how one might use the infrastructure provided
Philip Reamese6625502015-02-25 23:22:43 +0000504by ``gc.statepoint``. This example GC is compatible with the
505:ref:`PlaceSafepoints` and :ref:`RewriteStatepointsForGC` utility passes
506which simplify ``gc.statepoint`` sequence insertion. If you need to build a
507custom GC strategy around the ``gc.statepoints`` mechanisms, it is recommended
508that you use this one as a starting point.
509
510This GC strategy does not support read or write barriers. As a result, these
511intrinsics are lowered to normal loads and stores.
512
513The stack map format generated by this GC strategy can be found in the
514:ref:`stackmap-section` using a format documented :ref:`here
515<statepoint-stackmap-format>`. This format is intended to be the standard
516format supported by LLVM going forward.
Philip Reamese78cf552015-02-24 19:44:46 +0000517
518
Philip Reames03f38362015-02-24 23:12:27 +0000519Custom GC Strategies
520====================
521
522If none of the built in GC strategy descriptions met your needs above, you will
523need to define a custom GCStrategy and possibly, a custom LLVM pass to perform
524lowering. Your best example of where to start defining a custom GCStrategy
525would be to look at one of the built in strategies.
526
527You may be able to structure this additional code as a loadable plugin library.
528Loadable plugins are sufficient if all you need is to enable a different
529combination of built in functionality, but if you need to provide a custom
530lowering pass, you will need to build a patched version of LLVM. If you think
531you need a patched build, please ask for advice on llvm-dev. There may be an
532easy way we can extend the support to make it work for your use case without
533requiring a custom build.
534
Philip Reames38263192015-02-24 23:34:24 +0000535Collector Requirements
536----------------------
537
538You should be able to leverage any existing collector library that includes the following elements:
539
540#. A memory allocator which exposes an allocation function your compiled
541 code can call.
542
543#. A binary format for the stack map. A stack map describes the location
544 of references at a safepoint and is used by precise collectors to identify
545 references within a stack frame on the machine stack. Note that collectors
546 which conservatively scan the stack don't require such a structure.
547
548#. A stack crawler to discover functions on the call stack, and enumerate the
549 references listed in the stack map for each call site.
550
551#. A mechanism for identifying references in global locations (e.g. global
552 variables).
553
554#. If you collector requires them, an LLVM IR implementation of your collectors
555 load and store barriers. Note that since many collectors don't require
556 barriers at all, LLVM defaults to lowering such barriers to normal loads
557 and stores unless you arrange otherwise.
558
Philip Reames03f38362015-02-24 23:12:27 +0000559
Sean Silva18dc5382012-12-09 15:52:47 +0000560Implementing a collector plugin
Philip Reames03f38362015-02-24 23:12:27 +0000561-------------------------------
Sean Silva18dc5382012-12-09 15:52:47 +0000562
563User code specifies which GC code generation to use with the ``gc`` function
564attribute or, equivalently, with the ``setGC`` method of ``Function``.
565
566To implement a GC plugin, it is necessary to subclass ``llvm::GCStrategy``,
567which can be accomplished in a few lines of boilerplate code. LLVM's
568infrastructure provides access to several important algorithms. For an
569uncontroversial collector, all that remains may be to compile LLVM's computed
570stack map to assembly code (using the binary representation expected by the
571runtime library). This can be accomplished in about 100 lines of code.
572
573This is not the appropriate place to implement a garbage collected heap or a
574garbage collector itself. That code should exist in the language's runtime
575library. The compiler plugin is responsible for generating code which conforms
576to the binary interface defined by library, most essentially the :ref:`stack map
577<stack-map>`.
578
579To subclass ``llvm::GCStrategy`` and register it with the compiler:
580
581.. code-block:: c++
582
583 // lib/MyGC/MyGC.cpp - Example LLVM GC plugin
584
585 #include "llvm/CodeGen/GCStrategy.h"
586 #include "llvm/CodeGen/GCMetadata.h"
587 #include "llvm/Support/Compiler.h"
588
589 using namespace llvm;
590
591 namespace {
592 class LLVM_LIBRARY_VISIBILITY MyGC : public GCStrategy {
593 public:
594 MyGC() {}
595 };
596
597 GCRegistry::Add<MyGC>
598 X("mygc", "My bespoke garbage collector.");
599 }
600
601This boilerplate collector does nothing. More specifically:
602
603* ``llvm.gcread`` calls are replaced with the corresponding ``load``
604 instruction.
605
606* ``llvm.gcwrite`` calls are replaced with the corresponding ``store``
607 instruction.
608
609* No safe points are added to the code.
610
611* The stack map is not compiled into the executable.
612
Rafael Espindola730df072014-03-12 22:40:22 +0000613Using the LLVM makefiles, this code
Sean Silva18dc5382012-12-09 15:52:47 +0000614can be compiled as a plugin using a simple makefile:
615
616.. code-block:: make
617
618 # lib/MyGC/Makefile
619
620 LEVEL := ../..
621 LIBRARYNAME = MyGC
622 LOADABLE_MODULE = 1
623
624 include $(LEVEL)/Makefile.common
625
626Once the plugin is compiled, code using it may be compiled using ``llc
627-load=MyGC.so`` (though MyGC.so may have some other platform-specific
628extension):
629
630::
631
632 $ cat sample.ll
633 define void @f() gc "mygc" {
634 entry:
Bill Wendling547a7af2013-10-18 23:09:06 +0000635 ret void
Sean Silva18dc5382012-12-09 15:52:47 +0000636 }
637 $ llvm-as < sample.ll | llc -load=MyGC.so
638
639It is also possible to statically link the collector plugin into tools, such as
640a language-specific compiler front-end.
641
642.. _collector-algos:
643
644Overview of available features
645------------------------------
646
647``GCStrategy`` provides a range of features through which a plugin may do useful
648work. Some of these are callbacks, some are algorithms that can be enabled,
649disabled, or customized. This matrix summarizes the supported (and planned)
650features and correlates them with the collection techniques which typically
651require them.
652
653.. |v| unicode:: 0x2714
654 :trim:
655
656.. |x| unicode:: 0x2718
657 :trim:
658
659+------------+------+--------+----------+-------+---------+-------------+----------+------------+
660| Algorithm | Done | Shadow | refcount | mark- | copying | incremental | threaded | concurrent |
661| | | stack | | sweep | | | | |
662+============+======+========+==========+=======+=========+=============+==========+============+
663| stack map | |v| | | | |x| | |x| | |x| | |x| | |x| |
664+------------+------+--------+----------+-------+---------+-------------+----------+------------+
665| initialize | |v| | |x| | |x| | |x| | |x| | |x| | |x| | |x| |
666| roots | | | | | | | | |
667+------------+------+--------+----------+-------+---------+-------------+----------+------------+
668| derived | NO | | | | | | **N**\* | **N**\* |
669| pointers | | | | | | | | |
670+------------+------+--------+----------+-------+---------+-------------+----------+------------+
671| **custom | |v| | | | | | | | |
672| lowering** | | | | | | | | |
673+------------+------+--------+----------+-------+---------+-------------+----------+------------+
674| *gcroot* | |v| | |x| | |x| | | | | | |
675+------------+------+--------+----------+-------+---------+-------------+----------+------------+
676| *gcwrite* | |v| | | |x| | | | |x| | | |x| |
677+------------+------+--------+----------+-------+---------+-------------+----------+------------+
678| *gcread* | |v| | | | | | | | |x| |
679+------------+------+--------+----------+-------+---------+-------------+----------+------------+
680| **safe | | | | | | | | |
681| points** | | | | | | | | |
682+------------+------+--------+----------+-------+---------+-------------+----------+------------+
683| *in | |v| | | | |x| | |x| | |x| | |x| | |x| |
684| calls* | | | | | | | | |
685+------------+------+--------+----------+-------+---------+-------------+----------+------------+
686| *before | |v| | | | | | | |x| | |x| |
687| calls* | | | | | | | | |
688+------------+------+--------+----------+-------+---------+-------------+----------+------------+
689| *for | NO | | | | | | **N** | **N** |
690| loops* | | | | | | | | |
691+------------+------+--------+----------+-------+---------+-------------+----------+------------+
692| *before | |v| | | | | | | |x| | |x| |
693| escape* | | | | | | | | |
694+------------+------+--------+----------+-------+---------+-------------+----------+------------+
695| emit code | NO | | | | | | **N** | **N** |
696| at safe | | | | | | | | |
697| points | | | | | | | | |
698+------------+------+--------+----------+-------+---------+-------------+----------+------------+
699| **output** | | | | | | | | |
700+------------+------+--------+----------+-------+---------+-------------+----------+------------+
701| *assembly* | |v| | | | |x| | |x| | |x| | |x| | |x| |
702+------------+------+--------+----------+-------+---------+-------------+----------+------------+
703| *JIT* | NO | | | **?** | **?** | **?** | **?** | **?** |
704+------------+------+--------+----------+-------+---------+-------------+----------+------------+
705| *obj* | NO | | | **?** | **?** | **?** | **?** | **?** |
706+------------+------+--------+----------+-------+---------+-------------+----------+------------+
707| live | NO | | | **?** | **?** | **?** | **?** | **?** |
708| analysis | | | | | | | | |
709+------------+------+--------+----------+-------+---------+-------------+----------+------------+
710| register | NO | | | **?** | **?** | **?** | **?** | **?** |
711| map | | | | | | | | |
712+------------+------+--------+----------+-------+---------+-------------+----------+------------+
713| \* Derived pointers only pose a hasard to copying collections. |
714+------------+------+--------+----------+-------+---------+-------------+----------+------------+
715| **?** denotes a feature which could be utilized if available. |
716+------------+------+--------+----------+-------+---------+-------------+----------+------------+
717
718To be clear, the collection techniques above are defined as:
719
720Shadow Stack
721 The mutator carefully maintains a linked list of stack roots.
722
723Reference Counting
724 The mutator maintains a reference count for each object and frees an object
725 when its count falls to zero.
726
727Mark-Sweep
728 When the heap is exhausted, the collector marks reachable objects starting
729 from the roots, then deallocates unreachable objects in a sweep phase.
730
731Copying
732 As reachability analysis proceeds, the collector copies objects from one heap
733 area to another, compacting them in the process. Copying collectors enable
734 highly efficient "bump pointer" allocation and can improve locality of
735 reference.
736
737Incremental
738 (Including generational collectors.) Incremental collectors generally have all
739 the properties of a copying collector (regardless of whether the mature heap
740 is compacting), but bring the added complexity of requiring write barriers.
741
742Threaded
743 Denotes a multithreaded mutator; the collector must still stop the mutator
744 ("stop the world") before beginning reachability analysis. Stopping a
745 multithreaded mutator is a complicated problem. It generally requires highly
Alp Tokercf218752014-06-30 18:57:16 +0000746 platform-specific code in the runtime, and the production of carefully
Sean Silva18dc5382012-12-09 15:52:47 +0000747 designed machine code at safe points.
748
749Concurrent
750 In this technique, the mutator and the collector run concurrently, with the
751 goal of eliminating pause times. In a *cooperative* collector, the mutator
752 further aids with collection should a pause occur, allowing collection to take
753 advantage of multiprocessor hosts. The "stop the world" problem of threaded
754 collectors is generally still present to a limited extent. Sophisticated
755 marking algorithms are necessary. Read barriers may be necessary.
756
757As the matrix indicates, LLVM's garbage collection infrastructure is already
758suitable for a wide variety of collectors, but does not currently extend to
759multithreaded programs. This will be added in the future as there is
760interest.
761
762.. _stack-map:
763
764Computing stack maps
765--------------------
766
767LLVM automatically computes a stack map. One of the most important features
768of a ``GCStrategy`` is to compile this information into the executable in
769the binary representation expected by the runtime library.
770
771The stack map consists of the location and identity of each GC root in the
772each function in the module. For each root:
773
774* ``RootNum``: The index of the root.
775
776* ``StackOffset``: The offset of the object relative to the frame pointer.
777
778* ``RootMetadata``: The value passed as the ``%metadata`` parameter to the
779 ``@llvm.gcroot`` intrinsic.
780
781Also, for the function as a whole:
782
783* ``getFrameSize()``: The overall size of the function's initial stack frame,
784 not accounting for any dynamic allocation.
785
786* ``roots_size()``: The count of roots in the function.
787
788To access the stack map, use ``GCFunctionMetadata::roots_begin()`` and
789-``end()`` from the :ref:`GCMetadataPrinter <assembly>`:
790
791.. code-block:: c++
792
793 for (iterator I = begin(), E = end(); I != E; ++I) {
794 GCFunctionInfo *FI = *I;
795 unsigned FrameSize = FI->getFrameSize();
796 size_t RootCount = FI->roots_size();
797
798 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin(),
799 RE = FI->roots_end();
800 RI != RE; ++RI) {
801 int RootNum = RI->Num;
802 int RootStackOffset = RI->StackOffset;
803 Constant *RootMetadata = RI->Metadata;
804 }
805 }
806
807If the ``llvm.gcroot`` intrinsic is eliminated before code generation by a
808custom lowering pass, LLVM will compute an empty stack map. This may be useful
809for collector plugins which implement reference counting or a shadow stack.
810
811.. _init-roots:
812
813Initializing roots to null: ``InitRoots``
814-----------------------------------------
815
816.. code-block:: c++
817
818 MyGC::MyGC() {
819 InitRoots = true;
820 }
821
822When set, LLVM will automatically initialize each root to ``null`` upon entry to
823the function. This prevents the GC's sweep phase from visiting uninitialized
824pointers, which will almost certainly cause it to crash. This initialization
825occurs before custom lowering, so the two may be used together.
826
827Since LLVM does not yet compute liveness information, there is no means of
828distinguishing an uninitialized stack root from an initialized one. Therefore,
829this feature should be used by all GC plugins. It is enabled by default.
830
Sean Silva18dc5382012-12-09 15:52:47 +0000831Custom lowering of intrinsics: ``CustomRoots``, ``CustomReadBarriers``, and ``CustomWriteBarriers``
832---------------------------------------------------------------------------------------------------
833
Philip Reames23cf2e22015-01-28 19:28:03 +0000834For GCs which use barriers or unusual treatment of stack roots, these
835flags allow the collector to perform arbitrary transformations of the
836LLVM IR:
Sean Silva18dc5382012-12-09 15:52:47 +0000837
838.. code-block:: c++
839
840 class MyGC : public GCStrategy {
841 public:
842 MyGC() {
843 CustomRoots = true;
844 CustomReadBarriers = true;
845 CustomWriteBarriers = true;
846 }
Sean Silva18dc5382012-12-09 15:52:47 +0000847 };
848
Philip Reames23cf2e22015-01-28 19:28:03 +0000849If any of these flags are set, LLVM suppresses its default lowering for
850the corresponding intrinsics. Instead, you must provide a custom Pass
851which lowers the intrinsics as desired. If you have opted in to custom
852lowering of a particular intrinsic your pass **must** eliminate all
853instances of the corresponding intrinsic in functions which opt in to
854your GC. The best example of such a pass is the ShadowStackGC and it's
855ShadowStackGCLowering pass.
Sean Silva18dc5382012-12-09 15:52:47 +0000856
Philip Reames23cf2e22015-01-28 19:28:03 +0000857There is currently no way to register such a custom lowering pass
858without building a custom copy of LLVM.
Sean Silva18dc5382012-12-09 15:52:47 +0000859
860.. _safe-points:
861
862Generating safe points: ``NeededSafePoints``
863--------------------------------------------
864
865LLVM can compute four kinds of safe points:
866
867.. code-block:: c++
868
869 namespace GC {
870 /// PointKind - The type of a collector-safe point.
871 ///
872 enum PointKind {
873 Loop, //< Instr is a loop (backwards branch).
874 Return, //< Instr is a return instruction.
875 PreCall, //< Instr is a call instruction.
876 PostCall //< Instr is the return address of a call.
877 };
878 }
879
880A collector can request any combination of the four by setting the
881``NeededSafePoints`` mask:
882
883.. code-block:: c++
884
885 MyGC::MyGC() {
886 NeededSafePoints = 1 << GC::Loop
887 | 1 << GC::Return
888 | 1 << GC::PreCall
889 | 1 << GC::PostCall;
890 }
891
892It can then use the following routines to access safe points.
893
894.. code-block:: c++
895
896 for (iterator I = begin(), E = end(); I != E; ++I) {
897 GCFunctionInfo *MD = *I;
898 size_t PointCount = MD->size();
899
900 for (GCFunctionInfo::iterator PI = MD->begin(),
901 PE = MD->end(); PI != PE; ++PI) {
902 GC::PointKind PointKind = PI->Kind;
903 unsigned PointNum = PI->Num;
904 }
905 }
906
907Almost every collector requires ``PostCall`` safe points, since these correspond
908to the moments when the function is suspended during a call to a subroutine.
909
910Threaded programs generally require ``Loop`` safe points to guarantee that the
911application will reach a safe point within a bounded amount of time, even if it
912is executing a long-running loop which contains no function calls.
913
914Threaded collectors may also require ``Return`` and ``PreCall`` safe points to
915implement "stop the world" techniques using self-modifying code, where it is
916important that the program not exit the function without reaching a safe point
917(because only the topmost function has been patched).
918
919.. _assembly:
920
921Emitting assembly code: ``GCMetadataPrinter``
922---------------------------------------------
923
924LLVM allows a plugin to print arbitrary assembly code before and after the rest
925of a module's assembly code. At the end of the module, the GC can compile the
926LLVM stack map into assembly code. (At the beginning, this information is not
927yet computed.)
928
929Since AsmWriter and CodeGen are separate components of LLVM, a separate abstract
930base class and registry is provided for printing assembly code, the
931``GCMetadaPrinter`` and ``GCMetadataPrinterRegistry``. The AsmWriter will look
932for such a subclass if the ``GCStrategy`` sets ``UsesMetadata``:
933
934.. code-block:: c++
935
936 MyGC::MyGC() {
937 UsesMetadata = true;
938 }
939
940This separation allows JIT-only clients to be smaller.
941
942Note that LLVM does not currently have analogous APIs to support code generation
943in the JIT, nor using the object writers.
944
945.. code-block:: c++
946
947 // lib/MyGC/MyGCPrinter.cpp - Example LLVM GC printer
948
949 #include "llvm/CodeGen/GCMetadataPrinter.h"
950 #include "llvm/Support/Compiler.h"
951
952 using namespace llvm;
953
954 namespace {
955 class LLVM_LIBRARY_VISIBILITY MyGCPrinter : public GCMetadataPrinter {
956 public:
Bill Wendling547a7af2013-10-18 23:09:06 +0000957 virtual void beginAssembly(AsmPrinter &AP);
Sean Silva18dc5382012-12-09 15:52:47 +0000958
Bill Wendling547a7af2013-10-18 23:09:06 +0000959 virtual void finishAssembly(AsmPrinter &AP);
Sean Silva18dc5382012-12-09 15:52:47 +0000960 };
961
962 GCMetadataPrinterRegistry::Add<MyGCPrinter>
963 X("mygc", "My bespoke garbage collector.");
964 }
965
Bill Wendling0b55b4a2013-10-18 23:11:25 +0000966The collector should use ``AsmPrinter`` to print portable assembly code. The
967collector itself contains the stack map for the entire module, and may access
968the ``GCFunctionInfo`` using its own ``begin()`` and ``end()`` methods. Here's
969a realistic example:
Sean Silva18dc5382012-12-09 15:52:47 +0000970
971.. code-block:: c++
972
973 #include "llvm/CodeGen/AsmPrinter.h"
Benjamin Kramer9f566a52013-07-08 19:59:35 +0000974 #include "llvm/IR/Function.h"
975 #include "llvm/IR/DataLayout.h"
Sean Silva18dc5382012-12-09 15:52:47 +0000976 #include "llvm/Target/TargetAsmInfo.h"
Benjamin Kramer9f566a52013-07-08 19:59:35 +0000977 #include "llvm/Target/TargetMachine.h"
Sean Silva18dc5382012-12-09 15:52:47 +0000978
Bill Wendling547a7af2013-10-18 23:09:06 +0000979 void MyGCPrinter::beginAssembly(AsmPrinter &AP) {
Sean Silva18dc5382012-12-09 15:52:47 +0000980 // Nothing to do.
981 }
982
Bill Wendling547a7af2013-10-18 23:09:06 +0000983 void MyGCPrinter::finishAssembly(AsmPrinter &AP) {
984 MCStreamer &OS = AP.OutStreamer;
Eric Christopherd9134482014-08-04 21:25:23 +0000985 unsigned IntPtrSize = AP.TM.getSubtargetImpl()->getDataLayout()->getPointerSize();
Sean Silva18dc5382012-12-09 15:52:47 +0000986
987 // Put this in the data section.
Bill Wendling547a7af2013-10-18 23:09:06 +0000988 OS.SwitchSection(AP.getObjFileLowering().getDataSection());
Sean Silva18dc5382012-12-09 15:52:47 +0000989
990 // For each function...
991 for (iterator FI = begin(), FE = end(); FI != FE; ++FI) {
992 GCFunctionInfo &MD = **FI;
993
Bill Wendling547a7af2013-10-18 23:09:06 +0000994 // A compact GC layout. Emit this data structure:
Sean Silva18dc5382012-12-09 15:52:47 +0000995 //
996 // struct {
997 // int32_t PointCount;
Bill Wendling547a7af2013-10-18 23:09:06 +0000998 // void *SafePointAddress[PointCount];
999 // int32_t StackFrameSize; // in words
1000 // int32_t StackArity;
1001 // int32_t LiveCount;
1002 // int32_t LiveOffsets[LiveCount];
Sean Silva18dc5382012-12-09 15:52:47 +00001003 // } __gcmap_<FUNCTIONNAME>;
1004
1005 // Align to address width.
Bill Wendling547a7af2013-10-18 23:09:06 +00001006 AP.EmitAlignment(IntPtrSize == 4 ? 2 : 3);
Sean Silva18dc5382012-12-09 15:52:47 +00001007
1008 // Emit PointCount.
Bill Wendling547a7af2013-10-18 23:09:06 +00001009 OS.AddComment("safe point count");
Sean Silva18dc5382012-12-09 15:52:47 +00001010 AP.EmitInt32(MD.size());
Sean Silva18dc5382012-12-09 15:52:47 +00001011
1012 // And each safe point...
1013 for (GCFunctionInfo::iterator PI = MD.begin(),
Bill Wendling547a7af2013-10-18 23:09:06 +00001014 PE = MD.end(); PI != PE; ++PI) {
Sean Silva18dc5382012-12-09 15:52:47 +00001015 // Emit the address of the safe point.
Bill Wendling547a7af2013-10-18 23:09:06 +00001016 OS.AddComment("safe point address");
1017 MCSymbol *Label = PI->Label;
1018 AP.EmitLabelPlusOffset(Label/*Hi*/, 0/*Offset*/, 4/*Size*/);
1019 }
Sean Silva18dc5382012-12-09 15:52:47 +00001020
Bill Wendling547a7af2013-10-18 23:09:06 +00001021 // Stack information never change in safe points! Only print info from the
1022 // first call-site.
1023 GCFunctionInfo::iterator PI = MD.begin();
Sean Silva18dc5382012-12-09 15:52:47 +00001024
Bill Wendling547a7af2013-10-18 23:09:06 +00001025 // Emit the stack frame size.
1026 OS.AddComment("stack frame size (in words)");
1027 AP.EmitInt32(MD.getFrameSize() / IntPtrSize);
Sean Silva18dc5382012-12-09 15:52:47 +00001028
Bill Wendling547a7af2013-10-18 23:09:06 +00001029 // Emit stack arity, i.e. the number of stacked arguments.
1030 unsigned RegisteredArgs = IntPtrSize == 4 ? 5 : 6;
1031 unsigned StackArity = MD.getFunction().arg_size() > RegisteredArgs ?
1032 MD.getFunction().arg_size() - RegisteredArgs : 0;
1033 OS.AddComment("stack arity");
1034 AP.EmitInt32(StackArity);
1035
1036 // Emit the number of live roots in the function.
1037 OS.AddComment("live root count");
1038 AP.EmitInt32(MD.live_size(PI));
1039
1040 // And for each live root...
1041 for (GCFunctionInfo::live_iterator LI = MD.live_begin(PI),
1042 LE = MD.live_end(PI);
1043 LI != LE; ++LI) {
1044 // Emit live root's offset within the stack frame.
1045 OS.AddComment("stack index (offset / wordsize)");
1046 AP.EmitInt32(LI->StackOffset);
Sean Silva18dc5382012-12-09 15:52:47 +00001047 }
1048 }
1049 }
1050
1051References
1052==========
1053
1054.. _appel89:
1055
1056[Appel89] Runtime Tags Aren't Necessary. Andrew W. Appel. Lisp and Symbolic
1057Computation 19(7):703-705, July 1989.
1058
1059.. _goldberg91:
1060
1061[Goldberg91] Tag-free garbage collection for strongly typed programming
1062languages. Benjamin Goldberg. ACM SIGPLAN PLDI'91.
1063
1064.. _tolmach94:
1065
1066[Tolmach94] Tag-free garbage collection using explicit type parameters. Andrew
1067Tolmach. Proceedings of the 1994 ACM conference on LISP and functional
1068programming.
1069
1070.. _henderson02:
1071
1072[Henderson2002] `Accurate Garbage Collection in an Uncooperative Environment
1073<http://citeseer.ist.psu.edu/henderson02accurate.html>`__