1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2 "http://www.w3.org/TR/html4/strict.dtd">
5 <meta http-equiv="Content-Type" Content="text/html; charset=UTF-8" >
6 <title>Accurate Garbage Collection with LLVM</title>
7 <link rel="stylesheet" href="llvm.css" type="text/css">
8 <style type="text/css">
9 .rowhead { text-align: left; background: inherit; }
10 .indent { padding-left: 1em; }
11 .optl { color: #BFBFBF; }
16 <div class="doc_title">
17 Accurate Garbage Collection with LLVM
21 <li><a href="#introduction">Introduction</a>
23 <li><a href="#feature">Goals and non-goals</a></li>
27 <li><a href="#quickstart">Getting started</a>
29 <li><a href="#quickstart-compiler">In your compiler</a></li>
30 <li><a href="#quickstart-runtime">In your runtime library</a></li>
31 <li><a href="#shadow-stack">About the shadow stack</a></li>
35 <li><a href="#core">Core support</a>
37 <li><a href="#gcattr">Specifying GC code generation:
38 <tt>gc "..."</tt></a></li>
39 <li><a href="#gcroot">Identifying GC roots on the stack:
40 <tt>llvm.gcroot</tt></a></li>
41 <li><a href="#barriers">Reading and writing references in the heap</a>
43 <li><a href="#gcwrite">Write barrier: <tt>llvm.gcwrite</tt></a></li>
44 <li><a href="#gcread">Read barrier: <tt>llvm.gcread</tt></a></li>
50 <li><a href="#plugin">Compiler plugin interface</a>
52 <li><a href="#collector-algos">Overview of available features</a></li>
53 <li><a href="#stack-map">Computing stack maps</a></li>
54 <li><a href="#init-roots">Initializing roots to null:
55 <tt>InitRoots</tt></a></li>
56 <li><a href="#custom">Custom lowering of intrinsics: <tt>CustomRoots</tt>,
57 <tt>CustomReadBarriers</tt>, and <tt>CustomWriteBarriers</tt></a></li>
58 <li><a href="#safe-points">Generating safe points:
59 <tt>NeededSafePoints</tt></a></li>
60 <li><a href="#assembly">Emitting assembly code:
61 <tt>GCMetadataPrinter</tt></a></li>
65 <li><a href="#runtime-impl">Implementing a collector runtime</a>
67 <li><a href="#gcdescriptors">Tracing GC pointers from heap
72 <li><a href="#references">References</a></li>
76 <div class="doc_author">
77 <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a> and
81 <!-- *********************************************************************** -->
82 <div class="doc_section">
83 <a name="introduction">Introduction</a>
85 <!-- *********************************************************************** -->
87 <div class="doc_text">
89 <p>Garbage collection is a widely used technique that frees the programmer from
90 having to know the lifetimes of heap objects, making software easier to produce
91 and maintain. Many programming languages rely on garbage collection for
92 automatic memory management. There are two primary forms of garbage collection:
93 conservative and accurate.</p>
95 <p>Conservative garbage collection often does not require any special support
96 from either the language or the compiler: it can handle non-type-safe
97 programming languages (such as C/C++) and does not require any special
98 information from the compiler. The
99 <a href="http://www.hpl.hp.com/personal/Hans_Boehm/gc/">Boehm collector</a> is
100 an example of a state-of-the-art conservative collector.</p>
102 <p>Accurate garbage collection requires the ability to identify all pointers in
103 the program at run-time (which requires that the source-language be type-safe in
104 most cases). Identifying pointers at run-time requires compiler support to
105 locate all places that hold live pointer variables at run-time, including the
106 <a href="#gcroot">processor stack and registers</a>.</p>
108 <p>Conservative garbage collection is attractive because it does not require any
109 special compiler support, but it does have problems. In particular, because the
110 conservative garbage collector cannot <i>know</i> that a particular word in the
111 machine is a pointer, it cannot move live objects in the heap (preventing the
112 use of compacting and generational GC algorithms) and it can occasionally suffer
113 from memory leaks due to integer values that happen to point to objects in the
114 program. In addition, some aggressive compiler transformations can break
115 conservative garbage collectors (though these seem rare in practice).</p>
117 <p>Accurate garbage collectors do not suffer from any of these problems, but
118 they can suffer from degraded scalar optimization of the program. In particular,
119 because the runtime must be able to identify and update all pointers active in
120 the program, some optimizations are less effective. In practice, however, the
121 locality and performance benefits of using aggressive garbage allocation
122 techniques dominates any low-level losses.</p>
124 <p>This document describes the mechanisms and interfaces provided by LLVM to
125 support accurate garbage collection.</p>
129 <!-- ======================================================================= -->
130 <div class="doc_subsection">
131 <a name="feature">Goals and non-goals</a>
134 <div class="doc_text">
136 <p>LLVM's intermediate representation provides <a href="#intrinsics">garbage
137 collection intrinsics</a> that offer support for a broad class of
138 collector models. For instance, the intrinsics permit:</p>
141 <li>semi-space collectors</li>
142 <li>mark-sweep collectors</li>
143 <li>generational collectors</li>
144 <li>reference counting</li>
145 <li>incremental collectors</li>
146 <li>concurrent collectors</li>
147 <li>cooperative collectors</li>
150 <p>We hope that the primitive support built into the LLVM IR is sufficient to
151 support a broad class of garbage collected languages including Scheme, ML, Java,
152 C#, Perl, Python, Lua, Ruby, other scripting languages, and more.</p>
154 <p>However, LLVM does not itself provide a garbage collector—this should
155 be part of your language's runtime library. LLVM provides a framework for
156 compile time <a href="#plugin">code generation plugins</a>. The role of these
157 plugins is to generate code and data structures which conforms to the <em>binary
158 interface</em> specified by the <em>runtime library</em>. This is similar to the
159 relationship between LLVM and DWARF debugging info, for example. The
160 difference primarily lies in the lack of an established standard in the domain
161 of garbage collection—thus the plugins.</p>
163 <p>The aspects of the binary interface with which LLVM's GC support is
167 <li>Creation of GC-safe points within code where collection is allowed to
169 <li>Computation of the stack map. For each safe point in the code, object
170 references within the stack frame must be identified so that the
171 collector may traverse and perhaps update them.</li>
172 <li>Write barriers when storing object references to the heap. These are
173 commonly used to optimize incremental scans in generational
175 <li>Emission of read barriers when loading object references. These are
176 useful for interoperating with concurrent collectors.</li>
179 <p>There are additional areas that LLVM does not directly address:</p>
182 <li>Registration of global roots with the runtime.</li>
183 <li>Registration of stack map entries with the runtime.</li>
184 <li>The functions used by the program to allocate memory, trigger a
185 collection, etc.</li>
186 <li>Computation or compilation of type maps, or registration of them with
187 the runtime. These are used to crawl the heap for object
191 <p>In general, LLVM's support for GC does not include features which can be
192 adequately addressed with other features of the IR and does not specify a
193 particular binary interface. On the plus side, this means that you should be
194 able to integrate LLVM with an existing runtime. On the other hand, it leaves
195 a lot of work for the developer of a novel language. However, it's easy to get
196 started quickly and scale up to a more sophisticated implementation as your
197 compiler matures.</p>
201 <!-- *********************************************************************** -->
202 <div class="doc_section">
203 <a name="quickstart">Getting started</a>
205 <!-- *********************************************************************** -->
207 <div class="doc_text">
209 <p>Using a GC with LLVM implies many things, for example:</p>
212 <li>Write a runtime library or find an existing one which implements a GC
214 <li>Implement a memory allocator.</li>
215 <li>Design a binary interface for the stack map, used to identify
216 references within a stack frame on the machine stack.*</li>
217 <li>Implement a stack crawler to discover functions on the call stack.*</li>
218 <li>Implement a registry for global roots.</li>
219 <li>Design a binary interface for type maps, used to identify references
220 within heap objects.</li>
221 <li>Implement a collection routine bringing together all of the above.</li>
223 <li>Emit compatible code from your compiler.<ul>
224 <li>Initialization in the main function.</li>
225 <li>Use the <tt>gc "..."</tt> attribute to enable GC code generation
226 (or <tt>F.setGC("...")</tt>).</li>
227 <li>Use <tt>@llvm.gcroot</tt> to mark stack roots.</li>
228 <li>Use <tt>@llvm.gcread</tt> and/or <tt>@llvm.gcwrite</tt> to
229 manipulate GC references, if necessary.</li>
230 <li>Allocate memory using the GC allocation routine provided by the
231 runtime library.</li>
232 <li>Generate type maps according to your runtime's binary interface.</li>
234 <li>Write a compiler plugin to interface LLVM with the runtime library.*<ul>
235 <li>Lower <tt>@llvm.gcread</tt> and <tt>@llvm.gcwrite</tt> to appropriate
236 code sequences.*</li>
237 <li>Compile LLVM's stack map to the binary form expected by the
240 <li>Load the plugin into the compiler. Use <tt>llc -load</tt> or link the
241 plugin statically with your language's compiler.*</li>
242 <li>Link program executables with the runtime.</li>
245 <p>To help with several of these tasks (those indicated with a *), LLVM
246 includes a highly portable, built-in ShadowStack code generator. It is compiled
247 into <tt>llc</tt> and works even with the interpreter and C backends.</p>
251 <!-- ======================================================================= -->
252 <div class="doc_subsection">
253 <a name="quickstart-compiler">In your compiler</a>
256 <div class="doc_text">
258 <p>To turn the shadow stack on for your functions, first call:</p>
260 <div class="doc_code"><pre
261 >F.setGC("shadow-stack");</pre></div>
263 <p>for each function your compiler emits. Since the shadow stack is built into
264 LLVM, you do not need to load a plugin.</p>
266 <p>Your compiler must also use <tt>@llvm.gcroot</tt> as documented.
267 Don't forget to create a root for each intermediate value that is generated
268 when evaluating an expression. In <tt>h(f(), g())</tt>, the result of
269 <tt>f()</tt> could easily be collected if evaluating <tt>g()</tt> triggers a
272 <p>There's no need to use <tt>@llvm.gcread</tt> and <tt>@llvm.gcwrite</tt> over
273 plain <tt>load</tt> and <tt>store</tt> for now. You will need them when
274 switching to a more advanced GC.</p>
278 <!-- ======================================================================= -->
279 <div class="doc_subsection">
280 <a name="quickstart-runtime">In your runtime</a>
283 <div class="doc_text">
285 <p>The shadow stack doesn't imply a memory allocation algorithm. A semispace
286 collector or building atop <tt>malloc</tt> are great places to start, and can
287 be implemented with very little code.</p>
289 <p>When it comes time to collect, however, your runtime needs to traverse the
290 stack roots, and for this it needs to integrate with the shadow stack. Luckily,
291 doing so is very simple. (This code is heavily commented to help you
292 understand the data structure, but there are only 20 lines of meaningful
297 <div class="doc_code"><pre
298 >/// @brief The map for a single function's stack frame. One of these is
299 /// compiled as constant data into the executable for each function.
301 /// Storage of metadata values is elided if the %metadata parameter to
302 /// @llvm.gcroot is null.
304 int32_t NumRoots; //< Number of roots in stack frame.
305 int32_t NumMeta; //< Number of metadata entries. May be < NumRoots.
306 const void *Meta[0]; //< Metadata for each root.
309 /// @brief A link in the dynamic shadow stack. One of these is embedded in the
310 /// stack frame of each function on the call stack.
312 StackEntry *Next; //< Link to next stack entry (the caller's).
313 const FrameMap *Map; //< Pointer to constant FrameMap.
314 void *Roots[0]; //< Stack roots (in-place array).
317 /// @brief The head of the singly-linked list of StackEntries. Functions push
318 /// and pop onto this in their prologue and epilogue.
320 /// Since there is only a global list, this technique is not threadsafe.
321 StackEntry *llvm_gc_root_chain;
323 /// @brief Calls Visitor(root, meta) for each GC root on the stack.
324 /// root and meta are exactly the values passed to
325 /// <tt>@llvm.gcroot</tt>.
327 /// Visitor could be a function to recursively mark live objects. Or it
328 /// might copy them to another heap or generation.
330 /// @param Visitor A function to invoke for every GC root on the stack.
331 void visitGCRoots(void (*Visitor)(void **Root, const void *Meta)) {
332 for (StackEntry *R = llvm_gc_root_chain; R; R = R->Next) {
335 // For roots [0, NumMeta), the metadata pointer is in the FrameMap.
336 for (unsigned e = R->Map->NumMeta; i != e; ++i)
337 Visitor(&R->Roots[i], R->Map->Meta[i]);
339 // For roots [NumMeta, NumRoots), the metadata pointer is null.
340 for (unsigned e = R->Map->NumRoots; i != e; ++i)
341 Visitor(&R->Roots[i], NULL);
345 <!-- ======================================================================= -->
346 <div class="doc_subsection">
347 <a name="shadow-stack">About the shadow stack</a>
350 <div class="doc_text">
352 <p>Unlike many GC algorithms which rely on a cooperative code generator to
353 compile stack maps, this algorithm carefully maintains a linked list of stack
354 roots [<a href="#henderson02">Henderson2002</a>]. This so-called "shadow stack"
355 mirrors the machine stack. Maintaining this data structure is slower than using
356 a stack map compiled into the executable as constant data, but has a significant
357 portability advantage because it requires no special support from the target
358 code generator, and does not require tricky platform-specific code to crawl
359 the machine stack.</p>
361 <p>The tradeoff for this simplicity and portability is:</p>
364 <li>High overhead per function call.</li>
365 <li>Not thread-safe.</li>
368 <p>Still, it's an easy way to get started. After your compiler and runtime are
369 up and running, writing a <a href="#plugin">plugin</a> will allow you to take
370 advantage of <a href="#collector-algos">more advanced GC features</a> of LLVM
371 in order to improve performance.</p>
375 <!-- *********************************************************************** -->
376 <div class="doc_section">
377 <a name="core">IR features</a><a name="intrinsics"></a>
379 <!-- *********************************************************************** -->
381 <div class="doc_text">
383 <p>This section describes the garbage collection facilities provided by the
384 <a href="LangRef.html">LLVM intermediate representation</a>. The exact behavior
385 of these IR features is specified by the binary interface implemented by a
386 <a href="#plugin">code generation plugin</a>, not by this document.</p>
388 <p>These facilities are limited to those strictly necessary; they are not
389 intended to be a complete interface to any garbage collector. A program will
390 need to interface with the GC library using the facilities provided by that
395 <!-- ======================================================================= -->
396 <div class="doc_subsection">
397 <a name="gcattr">Specifying GC code generation: <tt>gc "..."</tt></a>
400 <div class="doc_code"><tt>
401 define <i>ty</i> @<i>name</i>(...) <u>gc "<i>name</i>"</u> { ...
404 <div class="doc_text">
406 <p>The <tt>gc</tt> function attribute is used to specify the desired GC style
407 to the compiler. Its programmatic equivalent is the <tt>setGC</tt> method of
408 <tt>Function</tt>.</p>
410 <p>Setting <tt>gc "<i>name</i>"</tt> on a function triggers a search for a
411 matching code generation plugin "<i>name</i>"; it is that plugin which defines
412 the exact nature of the code generated to support GC. If none is found, the
413 compiler will raise an error.</p>
415 <p>Specifying the GC style on a per-function basis allows LLVM to link together
416 programs that use different garbage collection algorithms (or none at all).</p>
420 <!-- ======================================================================= -->
421 <div class="doc_subsection">
422 <a name="gcroot">Identifying GC roots on the stack: <tt>llvm.gcroot</tt></a>
425 <div class="doc_code"><tt>
426 void @llvm.gcroot(i8** %ptrloc, i8* %metadata)
429 <div class="doc_text">
431 <p>The <tt>llvm.gcroot</tt> intrinsic is used to inform LLVM that a stack
432 variable references an object on the heap and is to be tracked for garbage
433 collection. The exact impact on generated code is specified by a <a
434 href="#plugin">compiler plugin</a>.</p>
436 <p>A compiler which uses mem2reg to raise imperative code using <tt>alloca</tt>
437 into SSA form need only add a call to <tt>@llvm.gcroot</tt> for those variables
438 which a pointers into the GC heap.</p>
440 <p>It is also important to mark intermediate values with <tt>llvm.gcroot</tt>.
441 For example, consider <tt>h(f(), g())</tt>. Beware leaking the result of
442 <tt>f()</tt> in the case that <tt>g()</tt> triggers a collection.</p>
444 <p>The first argument <b>must</b> be a value referring to an alloca instruction
445 or a bitcast of an alloca. The second contains a pointer to metadata that
446 should be associated with the pointer, and <b>must</b> be a constant or global
447 value address. If your target collector uses tags, use a null pointer for
450 <p>The <tt>%metadata</tt> argument can be used to avoid requiring heap objects
451 to have 'isa' pointers or tag bits. [<a href="#appel89">Appel89</a>, <a
452 href="#goldberg91">Goldberg91</a>, <a href="#tolmach94">Tolmach94</a>] If
453 specified, its value will be tracked along with the location of the pointer in
456 <p>Consider the following fragment of Java code:</p>
460 Object X; // A null-initialized reference to an object
465 <p>This block (which may be located in the middle of a function or in a loop
466 nest), could be compiled to this LLVM code:</p>
470 ;; In the entry block for the function, allocate the
471 ;; stack space for X, which is an LLVM pointer.
474 ;; Tell LLVM that the stack space is a stack root.
475 ;; Java has type-tags on objects, so we pass null as metadata.
476 %tmp = bitcast %Object** %X to i8**
477 call void @llvm.gcroot(i8** %X, i8* null)
480 ;; "CodeBlock" is the block corresponding to the start
481 ;; of the scope above.
483 ;; Java null-initializes pointers.
484 store %Object* null, %Object** %X
488 ;; As the pointer goes out of scope, store a null value into
489 ;; it, to indicate that the value is no longer live.
490 store %Object* null, %Object** %X
496 <!-- ======================================================================= -->
497 <div class="doc_subsection">
498 <a name="barriers">Reading and writing references in the heap</a>
501 <div class="doc_text">
503 <p>Some collectors need to be informed when the mutator (the program that needs
504 garbage collection) either reads a pointer from or writes a pointer to a field
505 of a heap object. The code fragments inserted at these points are called
506 <em>read barriers</em> and <em>write barriers</em>, respectively. The amount of
507 code that needs to be executed is usually quite small and not on the critical
508 path of any computation, so the overall performance impact of the barrier is
511 <p>Barriers often require access to the <em>object pointer</em> rather than the
512 <em>derived pointer</em> (which is a pointer to the field within the
513 object). Accordingly, these intrinsics take both pointers as separate arguments
514 for completeness. In this snippet, <tt>%object</tt> is the object pointer, and
515 <tt>%derived</tt> is the derived pointer:</p>
519 %class.Array = type { %class.Object, i32, [0 x %class.Object*] }
522 ;; Load the object pointer from a gcroot.
523 %object = load %class.Array** %object_addr
525 ;; Compute the derived pointer.
526 %derived = getelementptr %object, i32 0, i32 2, i32 %n</pre></blockquote>
528 <p>The use of these intrinsics is naturally optional if the target GC does
529 require the corresponding barrier. If so, the GC plugin will replace the
530 intrinsic calls with the corresponding <tt>load</tt> or <tt>store</tt>
531 instruction if they are used.</p>
533 <p>LLVM does not enforce any particular relationship between the object and
534 derived pointer (although a <a href="#plugin">plugin</a> might). However, it
535 would be unusual that the derived pointer not be a <tt>getelementptr</tt> of the
540 <!-- ======================================================================= -->
541 <div class="doc_subsubsection">
542 <a name="gcwrite">Write barrier: <tt>llvm.gcwrite</tt></a>
545 <div class="doc_code"><tt>
546 void @llvm.gcwrite(i8* %value, i8* %object, i8** %derived)
549 <div class="doc_text">
551 <p>For write barriers, LLVM provides the <tt>llvm.gcwrite</tt> intrinsic
552 function. It has exactly the same semantics as a non-volatile <tt>store</tt> to
553 the derived pointer (the third argument). The exact code generated is specified
554 by a <a href="#plugin">compiler plugin</a>.</p>
556 <p>Many important algorithms require write barriers, including generational
557 and concurrent collectors. Additionally, write barriers could be used to
558 implement reference counting.</p>
562 <!-- ======================================================================= -->
563 <div class="doc_subsubsection">
564 <a name="gcread">Read barrier: <tt>llvm.gcread</tt></a>
567 <div class="doc_code"><tt>
568 i8* @llvm.gcread(i8* %object, i8** %derived)<br>
571 <div class="doc_text">
573 <p>For read barriers, LLVM provides the <tt>llvm.gcread</tt> intrinsic function.
574 It has exactly the same semantics as a non-volatile <tt>load</tt> from the
575 derived pointer (the second argument). The exact code generated is specified by
576 a <a href="#plugin">compiler plugin</a>.</p>
578 <p>Read barriers are needed by fewer algorithms than write barriers, and may
579 have a greater performance impact since pointer reads are more frequent than
584 <!-- *********************************************************************** -->
585 <div class="doc_section">
586 <a name="plugin">Implementing a collector plugin</a>
588 <!-- *********************************************************************** -->
590 <div class="doc_text">
592 <p>User code specifies which GC code generation to use with the <tt>gc</tt>
593 function attribute or, equivalently, with the <tt>setGC</tt> method of
594 <tt>Function</tt>.</p>
596 <p>To implement a GC plugin, it is necessary to subclass
597 <tt>llvm::GCStrategy</tt>, which can be accomplished in a few lines of
598 boilerplate code. LLVM's infrastructure provides access to several important
599 algorithms. For an uncontroversial collector, all that remains may be to
600 compile LLVM's computed stack map to assembly code (using the binary
601 representation expected by the runtime library). This can be accomplished in
602 about 100 lines of code.</p>
604 <p>This is not the appropriate place to implement a garbage collected heap or a
605 garbage collector itself. That code should exist in the language's runtime
606 library. The compiler plugin is responsible for generating code which
607 conforms to the binary interface defined by library, most essentially the
608 <a href="#stack-map">stack map</a>.</p>
610 <p>To subclass <tt>llvm::GCStrategy</tt> and register it with the compiler:</p>
612 <blockquote><pre>// lib/MyGC/MyGC.cpp - Example LLVM GC plugin
614 #include "llvm/CodeGen/GCStrategy.h"
615 #include "llvm/CodeGen/GCMetadata.h"
616 #include "llvm/Support/Compiler.h"
618 using namespace llvm;
621 class VISIBILITY_HIDDEN MyGC : public GCStrategy {
626 GCRegistry::Add<MyGC>
627 X("mygc", "My bespoke garbage collector.");
630 <p>This boilerplate collector does nothing. More specifically:</p>
633 <li><tt>llvm.gcread</tt> calls are replaced with the corresponding
634 <tt>load</tt> instruction.</li>
635 <li><tt>llvm.gcwrite</tt> calls are replaced with the corresponding
636 <tt>store</tt> instruction.</li>
637 <li>No safe points are added to the code.</li>
638 <li>The stack map is not compiled into the executable.</li>
641 <p>Using the LLVM makefiles (like the <a
642 href="http://llvm.org/viewvc/llvm-project/llvm/trunk/projects/sample/">sample
643 project</a>), this code can be compiled as a plugin using a simple
650 LIBRARYNAME = <var>MyGC</var>
653 include $(LEVEL)/Makefile.common</pre></blockquote>
655 <p>Once the plugin is compiled, code using it may be compiled using <tt>llc
656 -load=<var>MyGC.so</var></tt> (though <var>MyGC.so</var> may have some other
657 platform-specific extension):</p>
661 define void @f() gc "mygc" {
665 $ llvm-as < sample.ll | llc -load=MyGC.so</pre></blockquote>
667 <p>It is also possible to statically link the collector plugin into tools, such
668 as a language-specific compiler front-end.</p>
672 <!-- ======================================================================= -->
673 <div class="doc_subsection">
674 <a name="collector-algos">Overview of available features</a>
677 <div class="doc_text">
679 <p><tt>GCStrategy</tt> provides a range of features through which a plugin
680 may do useful work. Some of these are callbacks, some are algorithms that can
681 be enabled, disabled, or customized. This matrix summarizes the supported (and
682 planned) features and correlates them with the collection techniques which
683 typically require them.</p>
689 <th>shadow stack</th>
698 <th class="rowhead"><a href="#stack-map">stack map</a></th>
709 <th class="rowhead"><a href="#init-roots">initialize roots</a></th>
719 <tr class="doc_warning">
720 <th class="rowhead">derived pointers</th>
731 <th class="rowhead"><em><a href="#custom">custom lowering</a></em></th>
742 <th class="rowhead indent">gcroot</th>
753 <th class="rowhead indent">gcwrite</th>
764 <th class="rowhead indent">gcread</th>
775 <th class="rowhead"><em><a href="#safe-points">safe points</a></em></th>
786 <th class="rowhead indent">in calls</th>
797 <th class="rowhead indent">before calls</th>
807 <tr class="doc_warning">
808 <th class="rowhead indent">for loops</th>
819 <th class="rowhead indent">before escape</th>
829 <tr class="doc_warning">
830 <th class="rowhead">emit code at safe points</th>
841 <th class="rowhead"><em>output</em></th>
852 <th class="rowhead indent"><a href="#assembly">assembly</a></th>
862 <tr class="doc_warning">
863 <th class="rowhead indent">JIT</th>
867 <td class="optl">✘</td>
868 <td class="optl">✘</td>
869 <td class="optl">✘</td>
870 <td class="optl">✘</td>
871 <td class="optl">✘</td>
873 <tr class="doc_warning">
874 <th class="rowhead indent">obj</th>
878 <td class="optl">✘</td>
879 <td class="optl">✘</td>
880 <td class="optl">✘</td>
881 <td class="optl">✘</td>
882 <td class="optl">✘</td>
884 <tr class="doc_warning">
885 <th class="rowhead">live analysis</th>
889 <td class="optl">✘</td>
890 <td class="optl">✘</td>
891 <td class="optl">✘</td>
892 <td class="optl">✘</td>
893 <td class="optl">✘</td>
895 <tr class="doc_warning">
896 <th class="rowhead">register map</th>
900 <td class="optl">✘</td>
901 <td class="optl">✘</td>
902 <td class="optl">✘</td>
903 <td class="optl">✘</td>
904 <td class="optl">✘</td>
908 <div><span class="doc_warning">*</span> Derived pointers only pose a
909 hazard to copying collectors.</div>
910 <div><span class="optl">✘</span> in gray denotes a feature which
911 could be utilized if available.</div>
916 <p>To be clear, the collection techniques above are defined as:</p>
919 <dt>Shadow Stack</dt>
920 <dd>The mutator carefully maintains a linked list of stack roots.</dd>
921 <dt>Reference Counting</dt>
922 <dd>The mutator maintains a reference count for each object and frees an
923 object when its count falls to zero.</dd>
925 <dd>When the heap is exhausted, the collector marks reachable objects starting
926 from the roots, then deallocates unreachable objects in a sweep
929 <dd>As reachability analysis proceeds, the collector copies objects from one
930 heap area to another, compacting them in the process. Copying collectors
931 enable highly efficient "bump pointer" allocation and can improve locality
934 <dd>(Including generational collectors.) Incremental collectors generally have
935 all the properties of a copying collector (regardless of whether the
936 mature heap is compacting), but bring the added complexity of requiring
939 <dd>Denotes a multithreaded mutator; the collector must still stop the mutator
940 ("stop the world") before beginning reachability analysis. Stopping a
941 multithreaded mutator is a complicated problem. It generally requires
942 highly platform specific code in the runtime, and the production of
943 carefully designed machine code at safe points.</dd>
945 <dd>In this technique, the mutator and the collector run concurrently, with
946 the goal of eliminating pause times. In a <em>cooperative</em> collector,
947 the mutator further aids with collection should a pause occur, allowing
948 collection to take advantage of multiprocessor hosts. The "stop the world"
949 problem of threaded collectors is generally still present to a limited
950 extent. Sophisticated marking algorithms are necessary. Read barriers may
954 <p>As the matrix indicates, LLVM's garbage collection infrastructure is already
955 suitable for a wide variety of collectors, but does not currently extend to
956 multithreaded programs. This will be added in the future as there is
961 <!-- ======================================================================= -->
962 <div class="doc_subsection">
963 <a name="stack-map">Computing stack maps</a>
966 <div class="doc_text">
968 <p>LLVM automatically computes a stack map. One of the most important features
969 of a <tt>GCStrategy</tt> is to compile this information into the executable in
970 the binary representation expected by the runtime library.</p>
972 <p>The stack map consists of the location and identity of each GC root in the
973 each function in the module. For each root:</p>
976 <li><tt>RootNum</tt>: The index of the root.</li>
977 <li><tt>StackOffset</tt>: The offset of the object relative to the frame
979 <li><tt>RootMetadata</tt>: The value passed as the <tt>%metadata</tt>
980 parameter to the <a href="#gcroot"><tt>@llvm.gcroot</tt></a> intrinsic.</li>
983 <p>Also, for the function as a whole:</p>
986 <li><tt>getFrameSize()</tt>: The overall size of the function's initial
987 stack frame, not accounting for any dynamic allocation.</li>
988 <li><tt>roots_size()</tt>: The count of roots in the function.</li>
991 <p>To access the stack map, use <tt>GCFunctionMetadata::roots_begin()</tt> and
992 -<tt>end()</tt> from the <tt><a
993 href="#assembly">GCMetadataPrinter</a></tt>:</p>
996 >for (iterator I = begin(), E = end(); I != E; ++I) {
997 GCFunctionInfo *FI = *I;
998 unsigned FrameSize = FI->getFrameSize();
999 size_t RootCount = FI->roots_size();
1001 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin(),
1002 RE = FI->roots_end();
1004 int RootNum = RI->Num;
1005 int RootStackOffset = RI->StackOffset;
1006 Constant *RootMetadata = RI->Metadata;
1008 }</pre></blockquote>
1010 <p>If the <tt>llvm.gcroot</tt> intrinsic is eliminated before code generation by
1011 a custom lowering pass, LLVM will compute an empty stack map. This may be useful
1012 for collector plugins which implement reference counting or a shadow stack.</p>
1017 <!-- ======================================================================= -->
1018 <div class="doc_subsection">
1019 <a name="init-roots">Initializing roots to null: <tt>InitRoots</tt></a>
1022 <div class="doc_text">
1027 }</pre></blockquote>
1029 <p>When set, LLVM will automatically initialize each root to <tt>null</tt> upon
1030 entry to the function. This prevents the GC's sweep phase from visiting
1031 uninitialized pointers, which will almost certainly cause it to crash. This
1032 initialization occurs before custom lowering, so the two may be used
1035 <p>Since LLVM does not yet compute liveness information, there is no means of
1036 distinguishing an uninitialized stack root from an initialized one. Therefore,
1037 this feature should be used by all GC plugins. It is enabled by default.</p>
1042 <!-- ======================================================================= -->
1043 <div class="doc_subsection">
1044 <a name="custom">Custom lowering of intrinsics: <tt>CustomRoots</tt>,
1045 <tt>CustomReadBarriers</tt>, and <tt>CustomWriteBarriers</tt></a>
1048 <div class="doc_text">
1050 <p>For GCs which use barriers or unusual treatment of stack roots, these
1051 flags allow the collector to perform arbitrary transformations of the LLVM
1055 >class MyGC : public GCStrategy {
1059 CustomReadBarriers = true;
1060 CustomWriteBarriers = true;
1063 virtual bool initializeCustomLowering(Module &M);
1064 virtual bool performCustomLowering(Function &F);
1065 };</pre></blockquote>
1067 <p>If any of these flags are set, then LLVM suppresses its default lowering for
1068 the corresponding intrinsics and instead calls
1069 <tt>performCustomLowering</tt>.</p>
1071 <p>LLVM's default action for each intrinsic is as follows:</p>
1074 <li><tt>llvm.gcroot</tt>: Leave it alone. The code generator must see it
1075 or the stack map will not be computed.</li>
1076 <li><tt>llvm.gcread</tt>: Substitute a <tt>load</tt> instruction.</li>
1077 <li><tt>llvm.gcwrite</tt>: Substitute a <tt>store</tt> instruction.</li>
1080 <p>If <tt>CustomReadBarriers</tt> or <tt>CustomWriteBarriers</tt> are specified,
1081 then <tt>performCustomLowering</tt> <strong>must</strong> eliminate the
1082 corresponding barriers.</p>
1084 <p><tt>performCustomLowering</tt> must comply with the same restrictions as <a
1085 href="WritingAnLLVMPass.html#runOnFunction"><tt
1086 >FunctionPass::runOnFunction</tt></a>.
1087 Likewise, <tt>initializeCustomLowering</tt> has the same semantics as <a
1088 href="WritingAnLLVMPass.html#doInitialization_mod"><tt
1089 >Pass::doInitialization(Module&)</tt></a>.</p>
1091 <p>The following can be used as a template:</p>
1094 >#include "llvm/Module.h"
1095 #include "llvm/IntrinsicInst.h"
1097 bool MyGC::initializeCustomLowering(Module &M) {
1101 bool MyGC::performCustomLowering(Function &F) {
1102 bool MadeChange = false;
1104 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1105 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; )
1106 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
1107 if (Function *F = CI->getCalledFunction())
1108 switch (F->getIntrinsicID()) {
1109 case Intrinsic::gcwrite:
1110 // Handle llvm.gcwrite.
1111 CI->eraseFromParent();
1114 case Intrinsic::gcread:
1115 // Handle llvm.gcread.
1116 CI->eraseFromParent();
1119 case Intrinsic::gcroot:
1120 // Handle llvm.gcroot.
1121 CI->eraseFromParent();
1127 }</pre></blockquote>
1132 <!-- ======================================================================= -->
1133 <div class="doc_subsection">
1134 <a name="safe-points">Generating safe points: <tt>NeededSafePoints</tt></a>
1137 <div class="doc_text">
1139 <p>LLVM can compute four kinds of safe points:</p>
1143 /// PointKind - The type of a collector-safe point.
1146 Loop, //< Instr is a loop (backwards branch).
1147 Return, //< Instr is a return instruction.
1148 PreCall, //< Instr is a call instruction.
1149 PostCall //< Instr is the return address of a call.
1151 }</pre></blockquote>
1153 <p>A collector can request any combination of the four by setting the
1154 <tt>NeededSafePoints</tt> mask:</p>
1158 NeededSafePoints = 1 << GC::Loop
1159 | 1 << GC::Return
1160 | 1 << GC::PreCall
1161 | 1 << GC::PostCall;
1162 }</pre></blockquote>
1164 <p>It can then use the following routines to access safe points.</p>
1167 >for (iterator I = begin(), E = end(); I != E; ++I) {
1168 GCFunctionInfo *MD = *I;
1169 size_t PointCount = MD->size();
1171 for (GCFunctionInfo::iterator PI = MD->begin(),
1172 PE = MD->end(); PI != PE; ++PI) {
1173 GC::PointKind PointKind = PI->Kind;
1174 unsigned PointNum = PI->Num;
1179 <p>Almost every collector requires <tt>PostCall</tt> safe points, since these
1180 correspond to the moments when the function is suspended during a call to a
1183 <p>Threaded programs generally require <tt>Loop</tt> safe points to guarantee
1184 that the application will reach a safe point within a bounded amount of time,
1185 even if it is executing a long-running loop which contains no function
1188 <p>Threaded collectors may also require <tt>Return</tt> and <tt>PreCall</tt>
1189 safe points to implement "stop the world" techniques using self-modifying code,
1190 where it is important that the program not exit the function without reaching a
1191 safe point (because only the topmost function has been patched).</p>
1196 <!-- ======================================================================= -->
1197 <div class="doc_subsection">
1198 <a name="assembly">Emitting assembly code: <tt>GCMetadataPrinter</tt></a>
1201 <div class="doc_text">
1203 <p>LLVM allows a plugin to print arbitrary assembly code before and after the
1204 rest of a module's assembly code. At the end of the module, the GC can compile
1205 the LLVM stack map into assembly code. (At the beginning, this information is not
1208 <p>Since AsmWriter and CodeGen are separate components of LLVM, a separate
1209 abstract base class and registry is provided for printing assembly code, the
1210 <tt>GCMetadaPrinter</tt> and <tt>GCMetadataPrinterRegistry</tt>. The AsmWriter
1211 will look for such a subclass if the <tt>GCStrategy</tt> sets
1212 <tt>UsesMetadata</tt>:</p>
1216 UsesMetadata = true;
1217 }</pre></blockquote>
1219 <p>This separation allows JIT-only clients to be smaller.</p>
1221 <p>Note that LLVM does not currently have analogous APIs to support code
1222 generation in the JIT, nor using the object writers.</p>
1225 >// lib/MyGC/MyGCPrinter.cpp - Example LLVM GC printer
1227 #include "llvm/CodeGen/GCMetadataPrinter.h"
1228 #include "llvm/Support/Compiler.h"
1230 using namespace llvm;
1233 class VISIBILITY_HIDDEN MyGCPrinter : public GCMetadataPrinter {
1235 virtual void beginAssembly(std::ostream &OS, AsmPrinter &AP,
1236 const TargetAsmInfo &TAI);
1238 virtual void finishAssembly(std::ostream &OS, AsmPrinter &AP,
1239 const TargetAsmInfo &TAI);
1242 GCMetadataPrinterRegistry::Add<MyGCPrinter>
1243 X("mygc", "My bespoke garbage collector.");
1244 }</pre></blockquote>
1246 <p>The collector should use <tt>AsmPrinter</tt> and <tt>TargetAsmInfo</tt> to
1247 print portable assembly code to the <tt>std::ostream</tt>. The collector itself
1248 contains the stack map for the entire module, and may access the
1249 <tt>GCFunctionInfo</tt> using its own <tt>begin()</tt> and <tt>end()</tt>
1250 methods. Here's a realistic example:</p>
1253 >#include "llvm/CodeGen/AsmPrinter.h"
1254 #include "llvm/Function.h"
1255 #include "llvm/Target/TargetMachine.h"
1256 #include "llvm/Target/TargetData.h"
1257 #include "llvm/Target/TargetAsmInfo.h"
1259 void MyGCPrinter::beginAssembly(std::ostream &OS, AsmPrinter &AP,
1260 const TargetAsmInfo &TAI) {
1264 void MyGCPrinter::finishAssembly(std::ostream &OS, AsmPrinter &AP,
1265 const TargetAsmInfo &TAI) {
1266 // Set up for emitting addresses.
1267 const char *AddressDirective;
1268 int AddressAlignLog;
1269 if (AP.TM.getTargetData()->getPointerSize() == sizeof(int32_t)) {
1270 AddressDirective = TAI.getData32bitsDirective();
1271 AddressAlignLog = 2;
1273 AddressDirective = TAI.getData64bitsDirective();
1274 AddressAlignLog = 3;
1277 // Put this in the data section.
1278 AP.SwitchToDataSection(TAI.getDataSection());
1280 // For each function...
1281 for (iterator FI = begin(), FE = end(); FI != FE; ++FI) {
1282 GCFunctionInfo &MD = **FI;
1284 // Emit this data structure:
1287 // int32_t PointCount;
1289 // void *SafePointAddress;
1290 // int32_t LiveCount;
1291 // int32_t LiveOffsets[LiveCount];
1292 // } Points[PointCount];
1293 // } __gcmap_<FUNCTIONNAME>;
1295 // Align to address width.
1296 AP.EmitAlignment(AddressAlignLog);
1298 // Emit the symbol by which the stack map entry can be found.
1300 Symbol += TAI.getGlobalPrefix();
1301 Symbol += "__gcmap_";
1302 Symbol += MD.getFunction().getName();
1303 if (const char *GlobalDirective = TAI.getGlobalDirective())
1304 OS << GlobalDirective << Symbol << "\n";
1305 OS << TAI.getGlobalPrefix() << Symbol << ":\n";
1308 AP.EmitInt32(MD.size());
1309 AP.EOL("safe point count");
1311 // And each safe point...
1312 for (GCFunctionInfo::iterator PI = MD.begin(),
1313 PE = MD.end(); PI != PE; ++PI) {
1314 // Align to address width.
1315 AP.EmitAlignment(AddressAlignLog);
1317 // Emit the address of the safe point.
1318 OS << AddressDirective
1319 << TAI.getPrivateGlobalPrefix() << "label" << PI->Num;
1320 AP.EOL("safe point address");
1322 // Emit the stack frame size.
1323 AP.EmitInt32(MD.getFrameSize());
1324 AP.EOL("stack frame size");
1326 // Emit the number of live roots in the function.
1327 AP.EmitInt32(MD.live_size(PI));
1328 AP.EOL("live root count");
1330 // And for each live root...
1331 for (GCFunctionInfo::live_iterator LI = MD.live_begin(PI),
1332 LE = MD.live_end(PI);
1334 // Print its offset within the stack frame.
1335 AP.EmitInt32(LI->StackOffset);
1336 AP.EOL("stack offset");
1346 <!-- *********************************************************************** -->
1347 <div class="doc_section">
1348 <a name="references">References</a>
1350 <!-- *********************************************************************** -->
1352 <div class="doc_text">
1354 <p><a name="appel89">[Appel89]</a> Runtime Tags Aren't Necessary. Andrew
1355 W. Appel. Lisp and Symbolic Computation 19(7):703-705, July 1989.</p>
1357 <p><a name="goldberg91">[Goldberg91]</a> Tag-free garbage collection for
1358 strongly typed programming languages. Benjamin Goldberg. ACM SIGPLAN
1361 <p><a name="tolmach94">[Tolmach94]</a> Tag-free garbage collection using
1362 explicit type parameters. Andrew Tolmach. Proceedings of the 1994 ACM
1363 conference on LISP and functional programming.</p>
1365 <p><a name="henderson02">[Henderson2002]</a> <a
1366 href="http://citeseer.ist.psu.edu/henderson02accurate.html">
1367 Accurate Garbage Collection in an Uncooperative Environment</a>.
1368 Fergus Henderson. International Symposium on Memory Management 2002.</p>
1373 <!-- *********************************************************************** -->
1377 <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
1378 src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
1379 <a href="http://validator.w3.org/check/referer"><img
1380 src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
1382 <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
1383 <a href="http://llvm.org">LLVM Compiler Infrastructure</a><br>
1384 Last modified: $Date$