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>Definition of a stack frame descriptor. For each safe point in the code,
170 a frame descriptor maps where object references are located within the
171 frame so that the GC may traverse and perhaps update them.</li>
172 <li>Write barriers when storing object references within the heap. These
173 are commonly used to optimize incremental scans.</li>
174 <li>Emission of read barriers when loading object references. These are
175 useful for interoperating with concurrent collectors.</li>
178 <p>There are additional areas that LLVM does not directly address:</p>
181 <li>Registration of global roots.</li>
182 <li>Discovery or registration of stack frame descriptors.</li>
183 <li>The functions used by the program to allocate memory, trigger a
184 collection, etc.</li>
187 <p>In general, LLVM's support for GC does not include features which can be
188 adequately addressed with other features of the IR and does not specify a
189 particular binary interface. On the plus side, this means that you should be
190 able to integrate LLVM with an existing runtime. On the other hand, it leaves
191 a lot of work for the developer of a novel language. However, it's easy to get
192 started quickly and scale up to a more sophisticated implementation as your
193 compiler matures.</p>
197 <!-- *********************************************************************** -->
198 <div class="doc_section">
199 <a name="quickstart">Getting started</a>
201 <!-- *********************************************************************** -->
203 <div class="doc_text">
205 <p>Using a GC with LLVM implies many things, for example:</p>
208 <li>Write a runtime library or find an existing one which implements a GC
210 <li>Implement a memory allocator.</li>
211 <li>Design a binary interface for frame descriptors, used to identify
212 references within a stack frame.*</li>
213 <li>Implement a stack crawler to discover functions on the call stack.*</li>
214 <li>Implement a registry for global roots.</li>
215 <li>Design a binary interface for type descriptors, used to map references
216 within heap objects.</li>
217 <li>Implement a collection routine bringing together all of the above.</li>
219 <li>Emit compatible code from your compiler.<ul>
220 <li>Initialization in the main function.</li>
221 <li>Use the <tt>gc "..."</tt> attribute to enable GC code generation
222 (or <tt>F.setGC("...")</tt>).</li>
223 <li>Use <tt>@llvm.gcroot</tt> to mark stack roots.</li>
224 <li>Use <tt>@llvm.gcread</tt> and/or <tt>@llvm.gcwrite</tt> to
225 manipulate GC references, if necessary.</li>
226 <li>Allocate memory using the GC allocation routine provided by the
227 runtime library.</li>
228 <li>Generate type descriptors according to your runtime's binary interface.</li>
230 <li>Write a compiler plugin to interface LLVM with the runtime library.*<ul>
231 <li>Lower <tt>@llvm.gcread</tt> and <tt>@llvm.gcwrite</tt> to appropriate
232 code sequences.*</li>
233 <li>Generate stack maps according to the runtime's binary interface.*</li>
235 <li>Load the plugin into the compiler. Use <tt>llc -load</tt> or link the
236 plugin statically with your language's compiler.*</li>
237 <li>Link program executables with the runtime.</li>
240 <p>To help with several of these tasks (those indicated with a *), LLVM
241 includes a highly portable, built-in ShadowStack code generator. It is compiled
242 into <tt>llc</tt> and works even with the interpreter and C backends.</p>
246 <!-- ======================================================================= -->
247 <div class="doc_subsection">
248 <a name="quickstart-compiler">In your compiler</a>
251 <div class="doc_text">
253 <p>To turn the shadow stack on for your functions, first call:</p>
255 <div class="doc_code"><pre
256 >F.setGC("shadow-stack");</pre></div>
258 <p>for each function your compiler emits. Since the shadow stack is built into
259 LLVM, you do not need to load a plugin.</p>
261 <p>Your compiler must also use <tt>@llvm.gcroot</tt> as documented.
262 Don't forget to create a root for each intermediate value that is generated
263 when evaluating an expression. In <tt>h(f(), g())</tt>, the result of
264 <tt>f()</tt> could easily be collected if evaluating <tt>g()</tt> triggers a
267 <p>There's no need to use <tt>@llvm.gcread</tt> and <tt>@llvm.gcwrite</tt> over
268 plain <tt>load</tt> and <tt>store</tt> for now. You will need them when
269 switching to a more advanced GC.</p>
273 <!-- ======================================================================= -->
274 <div class="doc_subsection">
275 <a name="quickstart-runtime">In your runtime</a>
278 <div class="doc_text">
280 <p>The shadow stack doesn't imply a memory allocation algorithm. A semispace
281 collector or building atop <tt>malloc</tt> are great places to start, and can
282 be implemented with very little code.</p>
284 <p>When it comes time to collect, however, your runtime needs to traverse the
285 stack roots, and for this it needs to integrate with the shadow stack. Luckily,
286 doing so is very simple. (This code is heavily commented to help you
287 understand the data structure, but there are only 20 lines of meaningful
292 <div class="doc_code"><pre
293 >/// @brief A constant shadow stack frame descriptor. The compiler emits one of
294 /// these for each function.
296 /// Storage of metadata values is elided if the %meta parameter to @llvm.gcroot
299 int32_t NumRoots; //< Number of roots in stack frame.
300 int32_t NumMeta; //< Number of metadata descriptors. May be < NumRoots.
301 const void *Meta[0]; //< Metadata for each root.
304 /// @brief A link in the dynamic shadow stack. One of these is embedded in the
305 /// stack frame of each function on the call stack.
307 StackEntry *Next; //< Link to next stack entry (the caller's).
308 const FrameMap *Map; //< Pointer to constant FrameMap.
309 void *Roots[0]; //< Stack roots (in-place array).
312 /// @brief The head of the singly-linked list of StackEntries. Functions push
313 /// and pop onto this in their prologue and epilogue.
315 /// Since there is only a global list, this technique is not threadsafe.
316 StackEntry *llvm_gc_root_chain;
318 /// @brief Calls Visitor(root, meta) for each GC root on the stack.
319 /// root and meta are exactly the values passed to
320 /// <tt>@llvm.gcroot</tt>.
322 /// Visitor could be a function to recursively mark live objects. Or it
323 /// might copy them to another heap or generation.
325 /// @param Visitor A function to invoke for every GC root on the stack.
326 void visitGCRoots(void (*Visitor)(void **Root, const void *Meta)) {
327 for (StackEntry *R = llvm_gc_root_chain; R; R = R->Next) {
330 // For roots [0, NumMeta), the metadata pointer is in the FrameMap.
331 for (unsigned e = R->Map->NumMeta; i != e; ++i)
332 Visitor(&R->Roots[i], R->Map->Meta[i]);
334 // For roots [NumMeta, NumRoots), the metadata pointer is null.
335 for (unsigned e = R->Map->NumRoots; i != e; ++i)
336 Visitor(&R->Roots[i], NULL);
340 <!-- ======================================================================= -->
341 <div class="doc_subsection">
342 <a name="shadow-stack">About the shadow stack</a>
345 <div class="doc_text">
347 <p>Unlike many GC algorithms which rely on a cooperative code generator to
348 generate stack maps, this algorithm carefully maintains a linked list of stack
349 root descriptors [<a href="#henderson02">Henderson2002</a>]. This so-called
350 "shadow stack" mirrors the machine stack. Maintaining this data structure is
351 slower than using stack maps, but has a significant portability advantage
352 because it requires no special support from the target code generator.</p>
354 <p>The tradeoff for this simplicity and portability is:</p>
357 <li>High overhead per function call.</li>
358 <li>Not thread-safe.</li>
361 <p>Still, it's an easy way to get started.</p>
365 <!-- *********************************************************************** -->
366 <div class="doc_section">
367 <a name="core">IR features</a><a name="intrinsics"></a>
369 <!-- *********************************************************************** -->
371 <div class="doc_text">
373 <p>This section describes the garbage collection facilities provided by the
374 <a href="LangRef.html">LLVM intermediate representation</a>. The exact behavior
375 of these IR features is specified by the binary interface implemented by a
376 <a href="#plugin">code generation plugin</a>, not by this document.</p>
378 <p>These facilities are limited to those strictly necessary; they are not
379 intended to be a complete interface to any garbage collector. A program will
380 need to interface with the GC library using the facilities provided by that
385 <!-- ======================================================================= -->
386 <div class="doc_subsection">
387 <a name="gcattr">Specifying GC code generation: <tt>gc "..."</tt></a>
390 <div class="doc_code"><tt>
391 define <i>ty</i> @<i>name</i>(...) <u>gc "<i>name</i>"</u> { ...
394 <div class="doc_text">
396 <p>The <tt>gc</tt> function attribute is used to specify the desired GC style
397 to the compiler. Its programmatic equivalent is the <tt>setGC</tt> method of
398 <tt>Function</tt>.</p>
400 <p>Setting <tt>gc "<i>name</i>"</tt> on a function triggers a search for a
401 matching code generation plugin "<i>name</i>"; it is that plugin which defines
402 the exact nature of the code generated to support GC. If none is found, the
403 compiler will raise an error.</p>
405 <p>Specifying the GC style on a per-function basis allows LLVM to link together
406 programs that use different garbage collection algorithms (or none at all).</p>
410 <!-- ======================================================================= -->
411 <div class="doc_subsection">
412 <a name="gcroot">Identifying GC roots on the stack: <tt>llvm.gcroot</tt></a>
415 <div class="doc_code"><tt>
416 void @llvm.gcroot(i8** %ptrloc, i8* %metadata)
419 <div class="doc_text">
421 <p>The <tt>llvm.gcroot</tt> intrinsic is used to inform LLVM that a stack
422 variable references an object on the heap and is to be tracked for garbage
423 collection. The exact impact on generated code is specified by a <a
424 href="#plugin">compiler plugin</a>.</p>
426 <p>A compiler which uses mem2reg to raise imperative code using <tt>alloca</tt>
427 into SSA form need only add a call to <tt>@llvm.gcroot</tt> for those variables
428 which a pointers into the GC heap.</p>
430 <p>It is also important to mark intermediate values with <tt>llvm.gcroot</tt>.
431 For example, consider <tt>h(f(), g())</tt>. Beware leaking the result of
432 <tt>f()</tt> in the case that <tt>g()</tt> triggers a collection.</p>
434 <p>The first argument <b>must</b> be a value referring to an alloca instruction
435 or a bitcast of an alloca. The second contains a pointer to metadata that
436 should be associated with the pointer, and <b>must</b> be a constant or global
437 value address. If your target collector uses tags, use a null pointer for
440 <p>The <tt>%metadata</tt> argument can be used to avoid requiring heap objects
441 to have 'isa' pointers or tag bits. [<a href="#appel89">Appel89</a>, <a
442 href="#goldberg91">Goldberg91</a>, <a href="#tolmach94">Tolmach94</a>] If
443 specified, its value will be tracked along with the location of the pointer in
446 <p>Consider the following fragment of Java code:</p>
450 Object X; // A null-initialized reference to an object
455 <p>This block (which may be located in the middle of a function or in a loop
456 nest), could be compiled to this LLVM code:</p>
460 ;; In the entry block for the function, allocate the
461 ;; stack space for X, which is an LLVM pointer.
464 ;; Tell LLVM that the stack space is a stack root.
465 ;; Java has type-tags on objects, so we pass null as metadata.
466 %tmp = bitcast %Object** %X to i8**
467 call void @llvm.gcroot(i8** %X, i8* null)
470 ;; "CodeBlock" is the block corresponding to the start
471 ;; of the scope above.
473 ;; Java null-initializes pointers.
474 store %Object* null, %Object** %X
478 ;; As the pointer goes out of scope, store a null value into
479 ;; it, to indicate that the value is no longer live.
480 store %Object* null, %Object** %X
486 <!-- ======================================================================= -->
487 <div class="doc_subsection">
488 <a name="barriers">Reading and writing references in the heap</a>
491 <div class="doc_text">
493 <p>Some collectors need to be informed when the mutator (the program that needs
494 garbage collection) either reads a pointer from or writes a pointer to a field
495 of a heap object. The code fragments inserted at these points are called
496 <em>read barriers</em> and <em>write barriers</em>, respectively. The amount of
497 code that needs to be executed is usually quite small and not on the critical
498 path of any computation, so the overall performance impact of the barrier is
501 <p>Barriers often require access to the <em>object pointer</em> rather than the
502 <em>derived pointer</em> (which is a pointer to the field within the
503 object). Accordingly, these intrinsics take both pointers as separate arguments
504 for completeness. In this snippet, <tt>%object</tt> is the object pointer, and
505 <tt>%derived</tt> is the derived pointer:</p>
509 %class.Array = type { %class.Object, i32, [0 x %class.Object*] }
512 ;; Load the object pointer from a gcroot.
513 %object = load %class.Array** %object_addr
515 ;; Compute the derived pointer.
516 %derived = getelementptr %object, i32 0, i32 2, i32 %n</pre></blockquote>
518 <p>The use of these intrinsics is naturally optional if the target GC does
519 require the corresponding barrier. If so, the GC plugin will replace the
520 intrinsic calls with the corresponding <tt>load</tt> or <tt>store</tt>
521 instruction if they are used.</p>
525 <!-- ======================================================================= -->
526 <div class="doc_subsubsection">
527 <a name="gcwrite">Write barrier: <tt>llvm.gcwrite</tt></a>
530 <div class="doc_code"><tt>
531 void @llvm.gcwrite(i8* %value, i8* %object, i8** %derived)
534 <div class="doc_text">
536 <p>For write barriers, LLVM provides the <tt>llvm.gcwrite</tt> intrinsic
537 function. It has exactly the same semantics as a non-volatile <tt>store</tt> to
538 the derived pointer (the third argument). The exact code generated is specified
539 by a <a href="#plugin">compiler plugin</a>.</p>
541 <p>Many important algorithms require write barriers, including generational
542 and concurrent collectors. Additionally, write barriers could be used to
543 implement reference counting.</p>
547 <!-- ======================================================================= -->
548 <div class="doc_subsubsection">
549 <a name="gcread">Read barrier: <tt>llvm.gcread</tt></a>
552 <div class="doc_code"><tt>
553 i8* @llvm.gcread(i8* %object, i8** %derived)<br>
556 <div class="doc_text">
558 <p>For read barriers, LLVM provides the <tt>llvm.gcread</tt> intrinsic function.
559 It has exactly the same semantics as a non-volatile <tt>load</tt> from the
560 derived pointer (the second argument). The exact code generated is specified by
561 a <a href="#plugin">compiler plugin</a>.</p>
563 <p>Read barriers are needed by fewer algorithms than write barriers, and may
564 have a greater performance impact since pointer reads are more frequent than
569 <!-- *********************************************************************** -->
570 <div class="doc_section">
571 <a name="plugin">Implementing a collector plugin</a>
573 <!-- *********************************************************************** -->
575 <div class="doc_text">
577 <p>User code specifies which GC code generation to use with the <tt>gc</tt>
578 function attribute or, equivalently, with the <tt>setGC</tt> method of
579 <tt>Function</tt>.</p>
581 <p>To implement a GC plugin, it is necessary to subclass
582 <tt>llvm::GCStrategy</tt>, which can be accomplished in a few lines of
583 boilerplate code. LLVM's infrastructure provides access to several important
584 algorithms. For an uncontroversial collector, all that remains may be to emit
585 the assembly code for the collector's unique stack map data structure, which
586 might be accomplished in as few as 100 LOC.</p>
588 <p>This is not the appropriate place to implement a garbage collected heap or a
589 garbage collector itself. That code should exist in the language's runtime
590 library. The compiler plugin is responsible for generating code which
591 conforms to the binary interface defined by library, most essentially the
592 <a href="stack-map">stack map</a>.</p>
594 <p>To subclass <tt>llvm::GCStrategy</tt> and register it with the compiler:</p>
596 <blockquote><pre>// lib/MyGC/MyGC.cpp - Example LLVM GC plugin
598 #include "llvm/CodeGen/GCStrategy.h"
599 #include "llvm/CodeGen/GCMetadata.h"
600 #include "llvm/Support/Compiler.h"
602 using namespace llvm;
605 class VISIBILITY_HIDDEN MyGC : public GCStrategy {
610 GCRegistry::Add<MyGC>
611 X("mygc", "My bespoke garbage collector.");
614 <p>Using the LLVM makefiles (like the <a
615 href="http://llvm.org/viewvc/llvm-project/llvm/trunk/projects/sample/">sample
616 project</a>), this can be built into a plugin using a simple makefile:</p>
622 LIBRARYNAME = <var>MyGC</var>
625 include $(LEVEL)/Makefile.common</pre></blockquote>
627 <p>Once the plugin is compiled, code using it may be compiled using <tt>llc
628 -load=<var>MyGC.so</var></tt> (though <var>MyGC.so</var> may have some other
629 platform-specific extension):</p>
633 define void @f() gc "mygc" {
637 $ llvm-as < sample.ll | llc -load=MyGC.so</pre></blockquote>
639 <p>It is also possible to statically link the collector plugin into tools, such
640 as a language-specific compiler front-end.</p>
644 <!-- ======================================================================= -->
645 <div class="doc_subsection">
646 <a name="collector-algos">Overview of available features</a>
649 <div class="doc_text">
651 <p>The boilerplate collector above does nothing. More specifically:</p>
654 <li><tt>llvm.gcread</tt> calls are replaced with the corresponding
655 <tt>load</tt> instruction.</li>
656 <li><tt>llvm.gcwrite</tt> calls are replaced with the corresponding
657 <tt>store</tt> instruction.</li>
658 <li>No stack map is emitted, and no safe points are added.</li>
661 <p><tt>Collector</tt> provides a range of features through which a plugin
662 collector may do useful work. This matrix summarizes the supported (and planned)
663 features and correlates them with the collection techniques which typically
670 <th>shadow stack</th>
679 <th class="rowhead"><a href="#stack-map">stack map</a></th>
690 <th class="rowhead"><a href="#init-roots">initialize roots</a></th>
700 <tr class="doc_warning">
701 <th class="rowhead">derived pointers</th>
712 <th class="rowhead"><em><a href="#custom">custom lowering</a></em></th>
723 <th class="rowhead indent">gcroot</th>
734 <th class="rowhead indent">gcwrite</th>
745 <th class="rowhead indent">gcread</th>
756 <th class="rowhead"><em><a href="#safe-points">safe points</a></em></th>
767 <th class="rowhead indent">in calls</th>
778 <th class="rowhead indent">before calls</th>
788 <tr class="doc_warning">
789 <th class="rowhead indent">for loops</th>
800 <th class="rowhead indent">before escape</th>
810 <tr class="doc_warning">
811 <th class="rowhead">emit code at safe points</th>
822 <th class="rowhead"><em>output</em></th>
833 <th class="rowhead indent"><a href="#assembly">assembly</a></th>
843 <tr class="doc_warning">
844 <th class="rowhead indent">JIT</th>
848 <td class="optl">✘</td>
849 <td class="optl">✘</td>
850 <td class="optl">✘</td>
851 <td class="optl">✘</td>
852 <td class="optl">✘</td>
854 <tr class="doc_warning">
855 <th class="rowhead indent">obj</th>
859 <td class="optl">✘</td>
860 <td class="optl">✘</td>
861 <td class="optl">✘</td>
862 <td class="optl">✘</td>
863 <td class="optl">✘</td>
865 <tr class="doc_warning">
866 <th class="rowhead">live analysis</th>
870 <td class="optl">✘</td>
871 <td class="optl">✘</td>
872 <td class="optl">✘</td>
873 <td class="optl">✘</td>
874 <td class="optl">✘</td>
876 <tr class="doc_warning">
877 <th class="rowhead">register map</th>
881 <td class="optl">✘</td>
882 <td class="optl">✘</td>
883 <td class="optl">✘</td>
884 <td class="optl">✘</td>
885 <td class="optl">✘</td>
889 <div><span class="doc_warning">*</span> Derived pointers only pose a
890 hazard to copying collectors.</div>
891 <div><span class="optl">✘</span> in gray denotes a feature which
892 could be utilized if available.</div>
897 <p>To be clear, the collection techniques above are defined as:</p>
900 <dt>Shadow Stack</dt>
901 <dd>The mutator carefully maintains a linked list of stack root
903 <dt>Reference Counting</dt>
904 <dd>The mutator maintains a reference count for each object and frees an
905 object when its count falls to zero.</dd>
907 <dd>When the heap is exhausted, the collector marks reachable objects starting
908 from the roots, then deallocates unreachable objects in a sweep
911 <dd>As reachability analysis proceeds, the collector copies objects from one
912 heap area to another, compacting them in the process. Copying collectors
913 enable highly efficient "bump pointer" allocation and can improve locality
916 <dd>(Including generational collectors.) Incremental collectors generally have
917 all the properties of a copying collector (regardless of whether the
918 mature heap is compacting), but bring the added complexity of requiring
921 <dd>Denotes a multithreaded mutator; the collector must still stop the mutator
922 ("stop the world") before beginning reachability analysis. Stopping a
923 multithreaded mutator is a complicated problem. It generally requires
924 highly platform specific code in the runtime, and the production of
925 carefully designed machine code at safe points.</dd>
927 <dd>In this technique, the mutator and the collector run concurrently, with
928 the goal of eliminating pause times. In a <em>cooperative</em> collector,
929 the mutator further aids with collection should a pause occur, allowing
930 collection to take advantage of multiprocessor hosts. The "stop the world"
931 problem of threaded collectors is generally still present to a limited
932 extent. Sophisticated marking algorithms are necessary. Read barriers may
936 <p>As the matrix indicates, LLVM's garbage collection infrastructure is already
937 suitable for a wide variety of collectors, but does not currently extend to
938 multithreaded programs. This will be added in the future as there is
943 <!-- ======================================================================= -->
944 <div class="doc_subsection">
945 <a name="stack-map">Computing stack maps</a>
948 <div class="doc_text">
951 >for (iterator I = begin(), E = end(); I != E; ++I) {
952 GCFunctionInfo *FI = *I;
953 unsigned FrameSize = FI->getFrameSize();
954 size_t RootCount = FI->roots_size();
956 for (GCFunctionInfo::roots_iterator RI = FI->roots_begin(),
957 RE = FI->roots_end();
959 int RootNum = RI->Num;
960 int RootStackOffset = RI->StackOffset;
961 Constant *RootMetadata = RI->Metadata;
965 <p>LLVM automatically computes a stack map. All a <tt>GCStrategy</tt> needs to do
966 is access it using <tt>GCFunctionMetadata::roots_begin()</tt> and
967 -<tt>end()</tt>. If the <tt>llvm.gcroot</tt> intrinsic is eliminated before code
968 generation by a custom lowering pass, LLVM's stack map will be empty.</p>
973 <!-- ======================================================================= -->
974 <div class="doc_subsection">
975 <a name="init-roots">Initializing roots to null: <tt>InitRoots</tt></a>
978 <div class="doc_text">
985 <p>When set, LLVM will automatically initialize each root to <tt>null</tt> upon
986 entry to the function. This prevents the GC's sweep phase from visiting
987 uninitialized pointers, which will almost certainly cause it to crash. This
988 initialization occurs before custom lowering, so the two may be used
991 <p>Since LLVM does not yet compute liveness information, there is no means of
992 distinguishing an uninitialized stack root from an initialized one. Therefore,
993 this feature should be used by all GC plugins. It is enabled by default.</p>
998 <!-- ======================================================================= -->
999 <div class="doc_subsection">
1000 <a name="custom">Custom lowering of intrinsics: <tt>CustomRoots</tt>,
1001 <tt>CustomReadBarriers</tt>, and <tt>CustomWriteBarriers</tt></a>
1004 <div class="doc_text">
1006 <p>For GCs which use barriers or unusual treatment of stack roots, these
1007 flags allow the collector to perform arbitrary transformations of the LLVM
1011 >class MyGC : public GCStrategy {
1015 CustomReadBarriers = true;
1016 CustomWriteBarriers = true;
1019 virtual bool initializeCustomLowering(Module &M);
1020 virtual bool performCustomLowering(Function &F);
1021 };</pre></blockquote>
1023 <p>If any of these flags are set, then LLVM suppresses its default lowering for
1024 the corresponding intrinsics and instead calls
1025 <tt>performCustomLowering</tt>.</p>
1027 <p>LLVM's default action for each intrinsic is as follows:</p>
1030 <li><tt>llvm.gcroot</tt>: Pass through to the code generator to generate a
1032 <li><tt>llvm.gcread</tt>: Substitute a <tt>load</tt> instruction.</li>
1033 <li><tt>llvm.gcwrite</tt>: Substitute a <tt>store</tt> instruction.</li>
1036 <p>If <tt>CustomReadBarriers</tt> or <tt>CustomWriteBarriers</tt> are specified,
1037 then <tt>performCustomLowering</tt> <strong>must</strong> eliminate the
1038 corresponding barriers.</p>
1040 <p><tt>performCustomLowering</tt> must comply with the same restrictions as <a
1041 href="WritingAnLLVMPass.html#runOnFunction"><tt
1042 >FunctionPass::runOnFunction</tt></a>.
1043 Likewise, <tt>initializeCustomLowering</tt> has the same semantics as <a
1044 href="WritingAnLLVMPass.html#doInitialization_mod"><tt
1045 >Pass::doInitialization(Module&)</tt></a>.</p>
1047 <p>The following can be used as a template:</p>
1050 >#include "llvm/Module.h"
1051 #include "llvm/IntrinsicInst.h"
1053 bool MyGC::initializeCustomLowering(Module &M) {
1057 bool MyGC::performCustomLowering(Function &F) {
1058 bool MadeChange = false;
1060 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1061 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; )
1062 if (IntrinsicInst *CI = dyn_cast<IntrinsicInst>(II++))
1063 if (Function *F = CI->getCalledFunction())
1064 switch (F->getIntrinsicID()) {
1065 case Intrinsic::gcwrite:
1066 // Handle llvm.gcwrite.
1067 CI->eraseFromParent();
1070 case Intrinsic::gcread:
1071 // Handle llvm.gcread.
1072 CI->eraseFromParent();
1075 case Intrinsic::gcroot:
1076 // Handle llvm.gcroot.
1077 CI->eraseFromParent();
1083 }</pre></blockquote>
1088 <!-- ======================================================================= -->
1089 <div class="doc_subsection">
1090 <a name="safe-points">Generating safe points: <tt>NeededSafePoints</tt></a>
1093 <div class="doc_text">
1095 <p>LLVM can compute four kinds of safe points:</p>
1099 /// PointKind - The type of a collector-safe point.
1102 Loop, //< Instr is a loop (backwards branch).
1103 Return, //< Instr is a return instruction.
1104 PreCall, //< Instr is a call instruction.
1105 PostCall //< Instr is the return address of a call.
1107 }</pre></blockquote>
1109 <p>A collector can request any combination of the four by setting the
1110 <tt>NeededSafePoints</tt> mask:</p>
1114 NeededSafePoints = 1 << GC::Loop
1115 | 1 << GC::Return
1116 | 1 << GC::PreCall
1117 | 1 << GC::PostCall;
1118 }</pre></blockquote>
1120 <p>It can then use the following routines to access safe points.</p>
1123 >for (iterator I = begin(), E = end(); I != E; ++I) {
1124 GCFunctionInfo *MD = *I;
1125 size_t PointCount = MD->size();
1127 for (GCFunctionInfo::iterator PI = MD->begin(),
1128 PE = MD->end(); PI != PE; ++PI) {
1129 GC::PointKind PointKind = PI->Kind;
1130 unsigned PointNum = PI->Num;
1135 <p>Almost every collector requires <tt>PostCall</tt> safe points, since these
1136 correspond to the moments when the function is suspended during a call to a
1139 <p>Threaded programs generally require <tt>Loop</tt> safe points to guarantee
1140 that the application will reach a safe point within a bounded amount of time,
1141 even if it is executing a long-running loop which contains no function
1144 <p>Threaded collectors may also require <tt>Return</tt> and <tt>PreCall</tt>
1145 safe points to implement "stop the world" techniques using self-modifying code,
1146 where it is important that the program not exit the function without reaching a
1147 safe point (because only the topmost function has been patched).</p>
1152 <!-- ======================================================================= -->
1153 <div class="doc_subsection">
1154 <a name="assembly">Emitting assembly code: <tt>GCMetadataPrinter</tt></a>
1157 <div class="doc_text">
1159 <p>LLVM allows a GC to print arbitrary assembly code before and after the rest
1160 of a module's assembly code. At the end of the module, the GC can print stack
1161 maps built by the code generator. (At the beginning, this information is not
1164 <p>Since AsmWriter and CodeGen are separate components of LLVM, a separate
1165 abstract base class and registry is provided for printing assembly code, the
1166 <tt>GCMetadaPrinter</tt> and <tt>GCMetadataPrinterRegistry</tt>. The AsmWriter
1167 will look for such a subclass if the <tt>GCStrategy</tt> sets
1168 <tt>UsesMetadata</tt>:</p>
1172 UsesMetadata = true;
1173 }</pre></blockquote>
1175 <p>Note that LLVM does not currently have analogous APIs to support code
1176 generation in the JIT, nor using the object writers.</p>
1179 >// lib/MyGC/MyGCPrinter.cpp - Example LLVM GC printer
1181 #include "llvm/CodeGen/GCMetadataPrinter.h"
1182 #include "llvm/Support/Compiler.h"
1184 using namespace llvm;
1187 class VISIBILITY_HIDDEN MyGCPrinter : public GCMetadataPrinter {
1189 virtual void beginAssembly(std::ostream &OS, AsmPrinter &AP,
1190 const TargetAsmInfo &TAI);
1192 virtual void finishAssembly(std::ostream &OS, AsmPrinter &AP,
1193 const TargetAsmInfo &TAI);
1196 GCMetadataPrinterRegistry::Add<MyGCPrinter>
1197 X("mygc", "My bespoke garbage collector.");
1198 }</pre></blockquote>
1200 <p>The collector should use <tt>AsmPrinter</tt> and <tt>TargetAsmInfo</tt> to
1201 print portable assembly code to the <tt>std::ostream</tt>. The collector itself
1202 contains the stack map for the entire module, and may access the
1203 <tt>GCFunctionInfo</tt> using its own <tt>begin()</tt> and <tt>end()</tt>
1204 methods. Here's a realistic example:</p>
1207 >#include "llvm/CodeGen/AsmPrinter.h"
1208 #include "llvm/Function.h"
1209 #include "llvm/Target/TargetMachine.h"
1210 #include "llvm/Target/TargetData.h"
1211 #include "llvm/Target/TargetAsmInfo.h"
1213 void MyGCPrinter::beginAssembly(std::ostream &OS, AsmPrinter &AP,
1214 const TargetAsmInfo &TAI) {
1218 void MyGCPrinter::finishAssembly(std::ostream &OS, AsmPrinter &AP,
1219 const TargetAsmInfo &TAI) {
1220 // Set up for emitting addresses.
1221 const char *AddressDirective;
1222 int AddressAlignLog;
1223 if (AP.TM.getTargetData()->getPointerSize() == sizeof(int32_t)) {
1224 AddressDirective = TAI.getData32bitsDirective();
1225 AddressAlignLog = 2;
1227 AddressDirective = TAI.getData64bitsDirective();
1228 AddressAlignLog = 3;
1231 // Put this in the data section.
1232 AP.SwitchToDataSection(TAI.getDataSection());
1234 // For each function...
1235 for (iterator FI = begin(), FE = end(); FI != FE; ++FI) {
1236 GCFunctionInfo &MD = **FI;
1238 // Emit this data structure:
1241 // int32_t PointCount;
1243 // void *SafePointAddress;
1244 // int32_t LiveCount;
1245 // int32_t LiveOffsets[LiveCount];
1246 // } Points[PointCount];
1247 // } __gcmap_<FUNCTIONNAME>;
1249 // Align to address width.
1250 AP.EmitAlignment(AddressAlignLog);
1252 // Emit the symbol by which the stack map can be found.
1254 Symbol += TAI.getGlobalPrefix();
1255 Symbol += "__gcmap_";
1256 Symbol += MD.getFunction().getName();
1257 if (const char *GlobalDirective = TAI.getGlobalDirective())
1258 OS << GlobalDirective << Symbol << "\n";
1259 OS << TAI.getGlobalPrefix() << Symbol << ":\n";
1262 AP.EmitInt32(MD.size());
1263 AP.EOL("safe point count");
1265 // And each safe point...
1266 for (GCFunctionInfo::iterator PI = MD.begin(),
1267 PE = MD.end(); PI != PE; ++PI) {
1268 // Align to address width.
1269 AP.EmitAlignment(AddressAlignLog);
1271 // Emit the address of the safe point.
1272 OS << AddressDirective
1273 << TAI.getPrivateGlobalPrefix() << "label" << PI->Num;
1274 AP.EOL("safe point address");
1276 // Emit the stack frame size.
1277 AP.EmitInt32(MD.getFrameSize());
1278 AP.EOL("stack frame size");
1280 // Emit the number of live roots in the function.
1281 AP.EmitInt32(MD.live_size(PI));
1282 AP.EOL("live root count");
1284 // And for each live root...
1285 for (GCFunctionInfo::live_iterator LI = MD.live_begin(PI),
1286 LE = MD.live_end(PI);
1288 // Print its offset within the stack frame.
1289 AP.EmitInt32(LI->StackOffset);
1290 AP.EOL("stack offset");
1300 <!-- *********************************************************************** -->
1301 <div class="doc_section">
1302 <a name="references">References</a>
1304 <!-- *********************************************************************** -->
1306 <div class="doc_text">
1308 <p><a name="appel89">[Appel89]</a> Runtime Tags Aren't Necessary. Andrew
1309 W. Appel. Lisp and Symbolic Computation 19(7):703-705, July 1989.</p>
1311 <p><a name="goldberg91">[Goldberg91]</a> Tag-free garbage collection for
1312 strongly typed programming languages. Benjamin Goldberg. ACM SIGPLAN
1315 <p><a name="tolmach94">[Tolmach94]</a> Tag-free garbage collection using
1316 explicit type parameters. Andrew Tolmach. Proceedings of the 1994 ACM
1317 conference on LISP and functional programming.</p>
1319 <p><a name="henderson02">[Henderson2002]</a> <a
1320 href="http://citeseer.ist.psu.edu/henderson02accurate.html">
1321 Accurate Garbage Collection in an Uncooperative Environment</a>.
1322 Fergus Henderson. International Symposium on Memory Management 2002.</p>
1327 <!-- *********************************************************************** -->
1331 <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
1332 src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
1333 <a href="http://validator.w3.org/check/referer"><img
1334 src="http://www.w3.org/Icons/valid-html401-blue" alt="Valid HTML 4.01"></a>
1336 <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
1337 <a href="http://llvm.org">LLVM Compiler Infrastructure</a><br>
1338 Last modified: $Date$