2 % (c) The OBFUSCATION-THROUGH-GRATUITOUS-PREPROCESSOR-ABUSE Project,
3 % Glasgow University, 1990-1994
8 % o I think it would be worth making the connection with CPS explicit.
9 % Now that we have explicit activation records (on the stack), we can
10 % explain the whole system in terms of CPS and tail calls --- with the
11 % one requirement that we carefuly distinguish stack-allocated objects
12 % from heap-allocated objects.
15 % \documentstyle[preprint]{acmconf}
16 \documentclass[11pt]{article}
17 \oddsidemargin 0.1 in % Note that \oddsidemargin = \evensidemargin
18 \evensidemargin 0.1 in
19 \marginparwidth 0.85in % Narrow margins require narrower marginal notes
25 \newcommand{\note}[1]{{\em Note: #1}}
35 \setlength{\parskip}{0.15cm}
36 \setlength{\parsep}{0.15cm}
37 \setlength{\topsep}{0cm} % Reduces space before and after verbatim,
38 % which is implemented using trivlist
39 \setlength{\parindent}{0cm}
41 \renewcommand{\textfraction}{0.2}
42 \renewcommand{\floatpagefraction}{0.7}
46 \newcommand{\ToDo}[1]{{{\bf ToDo:}\sl #1}}
47 \newcommand{\Arg}[1]{\mbox{${\tt arg}_{#1}$}}
48 \newcommand{\bottom}{bottom} % foo, can't remember the symbol name
50 \title{The STG runtime system (revised)}
51 \author{Simon Peyton Jones \\ Glasgow University and Oregon Graduate Institute \and
52 Simon Marlow \\ Glasgow University \and
53 Alastair Reid \\ Yale University}
63 This document describes the GHC/Hugs run-time system. It serves as
64 a Glasgow/Yale/Nottingham ``contract'' about what the RTS does.
66 \subsection{New features compared to GHC 2.04}
69 \item The RTS supports mixed compiled/interpreted execution, so
70 that a program can consist of a mixture of GHC-compiled and Hugs-interpreted
73 \item CAFs are only retained if they are
74 reachable. Since they are referred to by implicit references buried
75 in code, this means that the garbage collector must traverse the whole
76 accessible code tree. This feature eliminates a whole class of painful
79 \item A running thread has only one stack, which contains a mixture
80 of pointers and non-pointers. Section~\ref{sect:stacks} describes how
81 we find out which is which. (GHC has used two stacks for some while.
82 Using one stack instead of two reduces register pressure, reduces the
83 size of update frames, and eliminates
84 ``stack-stubbing'' instructions.)
88 \subsection{Wish list}
90 Here's a list of things we'd like to support in the future.
92 \item Interrupts, speculative computation.
95 The SM could tune the size of the allocation arena, the number of
96 generations, etc taking into account residency, GC rate and page fault
100 There should be no need to specify the amnount of stack/heap space to
101 allocate when you started a program - let it just take as much or as
102 little as it wants. (It might be useful to be able to specify maximum
103 sizes and to be able to suggest an initial size.)
106 We could trigger a GC when all threads are blocked waiting for IO if
107 the allocation arena (or some of the generations) are nearly full.
111 \subsection{Configuration}
113 Some of the above features are expensive or less portable, so we
114 envision building a number of different configurations supporting
115 different subsets of the above features.
117 You can make the following choices:
120 Support for concurrency or parallelism. There are four
121 mutually-exclusive choices.
124 \item[@SEQUENTIAL@] No concurrency or parallelism support.
125 This configuration might not support interrupt recovery.
126 \item[@CONCURRENT@] Support for concurrency but not for parallelism.
127 \item[@CONCURRENT@+@GRANSIM@] Concurrency support and simulated parallelism.
128 \item[@CONCURRENT@+@PARALLEL@] Concurrency support and real parallelism.
131 \item @PROFILING@ adds cost-centre profiling.
133 \item @TICKY@ gathers internal statistics (often known as ``ticky-ticky'' code).
135 \item @DEBUG@ does internal consistency checks.
137 \item Persistence. (well, not yet).
140 Which garbage collector to use. At the moment we
141 only anticipate one, however.
144 \subsection{Terminology}
148 \item A {\em word} is (at least) 32 bits and can hold either a signed
151 \item A {\em pointer} is (at least) 32 bits and big enough to hold a
152 function pointer or a data pointer.
154 \item A {\em closure} is a (representation of) a value of a {\em pointed}
155 type. It may be in HNF or it may be unevaluated --- in either case, you can
156 try to evaluate it again.
158 \item A {\em thunk} is a (representation of) a value of a {\em pointed}
159 type which is {\em not} in HNF.
163 Occasionally, a field of a data structure must hold either a word or a
164 pointer. In such circumstances, it is {\em not safe} to assume that
165 words and pointers are the same size.
168 % More terminology to mention.
171 There are a few other system invariants which need to be mentioned ---
172 though not necessarily here:
176 \item The garbage collector never expands an object when it promotes
177 it to the old generation. This is important because the GC avoids
178 performing heap overflow checks by assuming that the amount added to
179 the old generation is no bigger than the current new generation.
183 %-----------------------------------------------------------------------------
184 \part{Evaluation Model}
185 \section{Compiled Execution}
187 This section describes the framework in which compiled code evaluates
188 expressions. Only at certain points will compiled code need to be
189 able to talk to the interpreted world; these are discussed in Section
190 \ref{sect:switching-worlds}.
192 \subsection{Calling conventions}
194 \subsubsection{The call/return registers}
196 One of the problems in designing a virtual machine is that we want it
197 abstract away from tedious machine details but still reveal enough of
198 the underlying hardware that we can make sensible decisions about code
199 generation. A major problem area is the use of registers in
200 call/return conventions. On a machine with lots of registers, it's
201 cheaper to pass arguments and results in registers than to pass them
202 on the stack. On a machine with very few registers, it's cheaper to
203 pass arguments and results on the stack than to use ``virtual
204 registers'' in memory. We therefore use a hybrid system: the first
205 $n$ arguments or results are passed in registers; and the remaining
206 arguments or results are passed on the stack. For register-poor
207 architectures, it is important that we allow $n=0$.
209 We'll label the arguments and results \Arg{1} \ldots \Arg{m} --- with
210 the understanding that \Arg{1} \ldots \Arg{n} are in registers and
211 \Arg{n+1} \ldots \Arg{m} are on top of the stack.
213 Note that the mapping of arguments \Arg{1} \ldots \Arg{n} to machine
214 registers depends on the {\em kinds} of the arguments. For example,
215 if the first argument is a Float, we might pass it in a different
216 register from if it is an Int. In fact, we might find that a given
217 architecture lets us pass varying numbers of arguments according to
218 their types. For example, if a CPU has 2 Int registers and 2 Float
219 registers then we could pass between 2 and 4 arguments in machine
220 registers --- depending on whether they all have the same kind or they
221 have different kinds.
223 \subsubsection{Entering closures}
225 To evaluate a closure we jump to the entry code for the closure
226 passing a pointer to the closure in \Arg{1} so that the entry code can
227 access its environment.
229 \subsubsection{Function call}
231 The function-call mechanism is obviously crucial. There are five different
235 \item {\em Known combinator (function with no free variables) and enough arguments.}
237 A fast call can be made: push excess arguments onto stack and jump to
238 function's {\em fast entry point} passing arguments in \Arg{1} \ldots
241 The {\em fast entry point} is only called with exactly the right
242 number of arguments (in \Arg{1} \ldots \Arg{m}) so it can instantly
243 start doing useful work without first testing whether it has enough
244 registers or having to pop them off the stack first.
246 \item {\em Known combinator and insufficient arguments.}
248 A slow call can be made: push all arguments onto stack and jump to
249 function's {\em slow entry point}.
251 Any unpointed arguments which are pushed on the stack must be tagged.
252 This means pushing an extra word on the stack below the unpointed
253 words, containing the number of unpointed words above it.
255 %Todo: forward ref about tagging?
258 The {\em slow entry point} might be called with insufficient arguments
259 and so it must test whether there are enough arguments on the stack.
260 This {\em argument satisfaction check} consists of checking that
261 @Su-Sp@ is big enough to hold all the arguments (including any tags).
265 \item If the argument satisfaction check fails, it is because there is
266 one or more update frames on the stack before the rest of the
267 arguments that the function needs. In this case, we construct a PAP
268 (partial application, section~\ref{sect:PAP}) containing the arguments
269 which are on the stack. The PAP construction code will return to the
270 update frame with the address of the PAP in \Arg{1}.
272 \item If the argument satisfaction check succeeds, we jump to the fast
273 entry point with the arguments in \Arg{1} \ldots \Arg{arity}.
275 If the fast entry point expects to receive some of \Arg{i} on the
276 stack, we can reduce the amount of movement required by making the
277 stack layout for the fast entry point look like the stack layout for
278 the slow entry point. Since the slow entry point is entered with the
279 first argument on the top of the stack and with tags in front of any
280 unpointed arguments, this means that if \Arg{i} is unpointed, there
281 should be space below it for a tag and that the highest numbered
282 argument should be passed on the top of the stack.
284 We usually arrange that the fast entry point is placed immediately
285 after the slow entry point --- so we can just ``fall through'' to the
286 fast entry point without performing a jump.
291 \item {\em Known function closure (function with free variables) and enough arguments.}
293 A fast call can be made: push excess arguments onto stack and jump to
294 function's {\em fast entry point} passing a pointer to closure in
295 \Arg{1} and arguments in \Arg{2} \ldots \Arg{m+1}.
297 Like the fast entry point for a combinator, the fast entry point for a
298 closure is only called with appropriate values in \Arg{1} \ldots
299 \Arg{m+1} so we can start work straight away. The pointer to the
300 closure is used to access the free variables of the closure.
303 \item {\em Known function closure and insufficient arguments.}
305 A slow call can be made: push all arguments onto stack and jump to the
306 closure's slow entry point passing a pointer to the closure in \Arg{1}.
308 Again, the slow entry point performs an argument satisfaction check
309 and either builds a PAP or pops the arguments off the stack into
310 \Arg{2} \ldots \Arg{m+1} and jumps to the fast entry point.
313 \item {\em Unknown function closure or thunk.}
315 Sometimes, the function being called is not statically identifiable.
316 Consider, for example, the @compose@ function:
318 compose f g x = f (g x)
320 Since @f@ and @g@ are passed as arguments to @compose@, the latter has
321 to make a heap call. In a heap call the arguments are pushed onto the
322 stack, and the closure bound to the function is entered. In the
323 example, a thunk for @(g x)@ will be allocated, (a pointer to it)
324 pushed on the stack, and the closure bound to @f@ will be
325 entered. That is, we will jump to @f@s entry point passing @f@ in
326 \Arg{1}. If \Arg{1} is passed on the stack, it is pushed on top of
327 the thunk for @(g x)@.
329 The {\em entry code} for an updateable thunk (which must have arity 0)
330 pushes an update frame on the stack and starts executing the body of
331 the closure --- using \Arg{1} to access any free variables. This is
332 described in more detail in section~\ref{sect:data-updates}.
334 The {\em entry code} for a non-updateable closure is just the
335 closure's slow entry point.
339 In addition to the above considerations, if there are \emph{too many}
340 arguments then the extra arguments are simply pushed on the stack with
343 To summarise, a closure's standard (slow) entry point performs the following:
345 \item[Argument satisfaction check.] (function closure only)
346 \item[Stack overflow check.]
347 \item[Heap overflow check.]
348 \item[Copy free variables out of closure.] %Todo: why?
349 \item[Eager black holing.] (updateable thunk only) %Todo: forward ref.
350 \item[Push update frame.]
351 \item[Evaluate body of closure.]
355 \subsection{Case expressions and return conventions}
356 \label{sect:return-conventions}
358 The {\em evaluation} of a thunk is always initiated by
359 a @case@ expression. For example:
364 The code for a @case@ expression looks like this:
367 \item Push the free variables of the branches on the stack (fv(@E@) in
369 \item Push a \emph{return address} on the stack.
370 \item Evaluate the scrutinee (@x@ in this case).
373 Once evaluation of the scrutinee is complete, execution resumes at the
374 return address, which points to the code for the expression @E@.
376 When execution resumes at the return point, there must be some {\em
377 return convention} that defines where the components of the pair, @a@
378 and @b@, can be found. The return convention varies according to the
379 type of the scrutinee @x@:
385 (A space for) the return address is left on the top of the stack.
386 Leaving the return address on the stack ensures that the top of the
387 stack contains a valid activation record
388 (section~\ref{sect:activation-records}) --- should a garbage collection
391 \item If @x@ has a pointed type (e.g.~a data constructor or a function),
392 a pointer to @x@ is returned in \Arg{1}.
394 \ToDo{Warn that components of E should be extracted as soon as
395 possible to avoid a space leak.}
397 \item If @x@ is an unpointed type (e.g.~@Int#@ or @Float#@), @x@ is
400 \item If @x@ is an unpointed tuple constructor, the components of @x@
401 are returned in \Arg{1} \ldots \Arg{n} but no object is constructed in
402 the heap. Unboxed tuple constructors are useful for functions which
403 want to return multiple values such as those used in an (explicitly
404 encoded) state monad:
406 \ToDo{Move stuff about unboxed tuples to a separate section}
409 data unpointed AAndState a = AnS a State
410 type S a = State -> AAndState a
412 bindS m k s0 = case m s0 of { AnS s1 a -> k s1 a }
413 returnS a s = AnS a s
416 Note that unboxed datatypes can only have one constructor and that
417 thunks never have unboxed types --- so we'll never try to update an
418 unboxed constructor. Unboxed tuples are \emph{never} built on the
421 When passing an unboxed tuple to a function, the components are
422 flattened out and passed in \Arg{1} \ldots \Arg{n} as usual.
426 \subsection{Vectored Returns}
428 Many algebraic data types have more than one constructor. For
429 example, the @Maybe@ type is defined like this:
431 data Maybe a = Nothing | Just a
433 How does the return convention encode which of the two constructors is
434 being returned? A @case@ expression scrutinising a value of @Maybe@
435 type would look like this:
441 Rather than pushing a return address before evaluating the scrutinee,
442 @E@, the @case@ expression pushes (a pointer to) a {\em return
443 vector}, a static table consisting of two code pointers: one for the
444 @Just@ alternative, and one for the @Nothing@ alternative.
450 The constructor @Nothing@ returns by jumping to the first item in the
451 return vector with a pointer to a (statically built) Nothing closure
454 It might seem that we could avoid loading \Arg{1} in this case since the
455 first item in the return vector will know that @Nothing@ was returned
456 (and can easily access the Nothing closure in the (unlikely) event
457 that it needs it. The only reason we load \Arg{1} is in case we have to
458 perform an update (section~\ref{sect:data-updates}).
462 The constructor @Just@ returns by jumping to the second element of the
463 return vector with a pointer to the closure in \Arg{1}.
467 In this way no test need be made to see which constructor returns;
468 instead, execution resumes immediately in the appropriate branch of
471 \subsection{Direct Returns}
473 When a datatype has a large number of constructors, it may be
474 inappropriate to use vectored returns. The vector tables may be
475 large and sparse, and it may be better to identify the constructor
476 using a test-and-branch sequence on the tag. For this reason, we
477 provide an alternative return convention, called a \emph{direct
480 In a direct return, the return address pushed on the stack really is a
481 code pointer. The returning code loads a pointer to the closure being
482 returned in \Arg{1} as usual, and also loads the tag into \Arg{2}.
483 The code at the return address will test the tag and jump to the
484 appropriate code for the case branch.
486 The choice of whether to use a vectored return or a direct return is
487 made on a type-by-type basis --- up to a certain maximum number of
488 constructors imposed by the update mechanism
489 (section~\ref{sect:data-updates}).
491 Single-constructor data types also use direct returns, although in
492 that case there is no need to return a tag in \Arg{2}.
494 \ToDo{Say whether we pop the return address before returning}
496 \ToDo{Stack stubbing?}
499 \label{sect:data-updates}
501 The entry code for an updatable thunk (which must also be of arity 0):
504 \item copies the free variables out of the thunk into registers or
506 \item pushes an {\em update frame} onto the stack.
508 An update frame is a small activation record consisting of
510 \begin{tabular}{|l|l|l|}
512 {\em Fixed header} & {\em Update Frame link} & {\em Updatee} \\
517 \note{In the semantics part of the STG paper (section 5.6), an update
518 frame consists of everything down to the last update frame on the
519 stack. This would make sense too --- and would fit in nicely with
520 what we're going to do when we add support for speculative
522 \ToDo{I think update frames contain cost centres sometimes}
525 If we are doing ``eager blackholing,'' we then overwrite the thunk
526 with a black hole. Otherwise, we leave it to the garbage collector to
527 black hole the thunk.
530 Start evaluating the body of the expression.
534 When the expression finishes evaluation, it will enter the update
535 frame on the top of the stack. Since the returner doesn't know
536 whether it is entering a normal return address/vector or an update
537 frame, we follow exactly the same conventions as return addresses and
538 return vectors. That is, on entering the update frame:
541 \item The value of the thunk is in \Arg{1}. (Recall that only thunks
542 are updateable and that thunks return just one value.)
544 \item If the data type is a direct-return type rather than a
545 vectored-return type, then the tag is in \Arg{2}.
547 \item The update frame is still on the stack.
550 We can safely share a single statically-compiled update function
551 between all types. However, the code must be able to handle both
552 vectored and direct-return datatypes. This is done by arranging that
553 the update code looks like this:
561 |---------------| <- update code pointer
566 Each entry in the return vector (which is large enough to cover the
567 largest vectored-return type) points to the update code.
571 \item overwrites the {\em updatee} with an indirection to \Arg{1};
572 \item loads @Su@ from the Update Frame link;
573 \item removes the update frame from the stack; and
574 \item enters \Arg{1}.
577 We enter \Arg{1} again, having probably just come from there, because
578 it knows whether to perform a direct or vectored return. This could
579 be optimised by compiling special update code for each slot in the
580 return vector, which performs the correct return.
582 \subsection{Semi-tagging}
583 \label{sect:semi-tagging}
585 When a @case@ expression evaluates a variable that might be bound
586 to a thunk it is often the case that the scrutinee is already evaluated.
587 In this case we have paid the penalty of (a) pushing the return address (or
588 return vector address) on the stack, (b) jumping through the info pointer
589 of the scrutinee, and (c) returning by an indirect jump through the
590 return address on the stack.
592 If we knew that the scrutinee was already evaluated we could generate
593 (better) code which simply jumps to the appropriate branch of the @case@
594 with a pointer to the scrutinee in \Arg{1}.
596 An obvious idea, therefore, is to test dynamically whether the heap
597 closure is a value (using the tag in the info table). If not, we
598 enter the closure as usual; if so, we jump straight to the appropriate
599 alternative. Here, for example, is pseudo-code for the expression
600 @(case x of { (a,_,c) -> E }@:
602 \Arg{1} = <pointer to x>;
603 tag = \Arg{1}->entry->tag;
605 Sp--; \\ insert space for return address
611 <info table for return address goes here>
612 ret: a = \Arg{1}->data1; \\ suck out a and c to avoid space leak
616 and here is the code for the expression @(case x of { [] -> E1; x:xs -> E2 }@:
618 \Arg{1} = <pointer to x>;
619 tag = \Arg{1}->entry->tag;
621 Sp--; \\ insert space for return address
629 retvec: \\ reversed return vector
630 <return info table for case goes here>
632 panic("Direct return into vectored case");
636 ret2: x = \Arg{1}->head;
640 There is an obvious cost in compiled code size (but none in the size
641 of the bytecodes). There is also a cost in execution time if we enter
642 more thunks than data constructors.
644 Both the direct and vectored returns are easily modified to chase chains
645 of indirections too. In the vectored case, this is most easily done by
646 making sure that @IND = TAG_1 - 1@, and adding an extra field to every
647 return vector. In the above example, the indirection code would be
649 ind: \Arg{1} = \Arg{1}->next;
652 where @ind_loop@ is the second line of code.
654 Note that we have to leave space for a return address since the return
655 address expects to find one. If the body of the expression requires a
656 heap check, we will actually have to write the return address before
657 entering the garbage collector.
660 \subsection{Heap and Stack Checks}
662 \note{I reckon these deserve a subsection of their own}
664 Don't move heap pointer before success occurs.
665 Talk about how stack check looks ahead into the branches of case expressions.
667 \subsection{Handling interrupts/signals}
670 May have to keep C stack pointer in register to placate OS?
671 May have to revert black holes - ouch!
674 \section{Interpreted Execution}
676 This section describes how the Hugs interpreter interprets code in the
677 same environment as compiled code executes. Both evaluation models
678 use a common garbage collector, so they must agree on the form of
681 Hugs interprets code by converting it to byte-code and applying a
682 byte-code interpreter to it. Wherever possible, we try to ensure that
683 the byte-code is all that is required to interpret a section of code.
684 This means not dynamically generating info tables, and hence we can
685 only have a small number of possible heap objects each with a staticly
686 compiled info table. Similarly for stack objects: in fact we only
687 have one Hugs stack object, in which all information is tagged for the
690 There is, however, one exception to this rule. Hugs must generate
691 info tables for any constructors it is asked to compile, since the
692 alternative is to force a context-switch each time compiled code
693 enters a Hugs-built constructor, which would be prohibitively
696 \subsection{Hugs Heap Objects}
697 \label{sect:hugs-heap-objects}
699 \subsubsection{Byte-Code Objects}
701 Compiled byte code lives on the global heap, in objects called
702 Byte-Code Objects (or BCOs). The layout of BCOs is described in
703 detail in Section \ref{sect:BCO}, in this section we will describe
706 Since byte-code lives on the heap, it can be garbage collected just
707 like any other heap-resident data. Hugs maintains a table of
708 currently live BCOs, which is treated as a table of live pointers by
709 the garbage collector. When a module is unloaded, the pointers to its
710 BCOs are removed from the table, and the code will be garbage
711 collected some time later.
713 A BCO represents a basic block of code - all entry points are at the
714 beginning of a BCO, and it is impossible to jump into the middle of
715 one. A BCO represents not only the code for a function, but also its
716 closure; a BCO can be entered just like any other closure. Hugs
717 performs lambda-lifting during compilation to byte-code, and each
718 top-level combinator becomes a BCO in the heap.
720 \subsubsection{Thunks and partial applications}
722 A thunk consists of a code pointer, and values for the free variables
723 of that code. Since Hugs byte-code is lambda-lifted, free variables
724 become arguments and are expected to be on the stack by the called
727 Hugs represents thunks with an @HUGS_AP@ object. The @HUGS_AP@ object
728 contains one or more pointers to other heap objects. When it is
729 entered, it pushes an update frame followed by its payload on the
730 stack, and enters the first word (which will be a pointer to a BCO).
731 The layout of @HUGS_AP@ objects is described in more detail in Section
734 Partial applications are represented by @HUGS_PAP@ objects, which are
735 identical to @HUGS_AP@s except that they are non-updatable.
737 \ToDo{Hugs Constructors}.
739 \subsection{Calling conventions}
740 \label{sect:hugs-calling-conventions}
742 The calling convention for any byte-code function is straightforward:
745 \item Push any arguments on the stack.
746 \item Push a pointer to the BCO.
747 \item Begin interpreting the byte code.
750 The @ENTER@ byte-code instruction decides how to enter its argument.
751 The object being entered must be either
758 \item A GHC-built closure, or
759 \item An indirection.
762 If @ENTER@ is applied to a BCO, we just begin interpreting the
763 byte-code contained therein. If the object is an @HUGS_AP@, we push an
764 update frame, push the values from the @HUGS_AP@ on the stack, and enter
765 its associated object. If the object is a @HUGS_PAP@, we push its
766 values on the stack and enter the first one. If the object is a
767 constructor, we simply return (see Section
768 \ref{sect:hugs-return-convention}). The fourth case is convered in
769 Section \ref{sect:hugs-to-ghc-closure}. If the object is an
770 indirection, we simply enter the object it points to.
772 \subsection{Return convention}
773 \label{sect:hugs-return-convention}
775 When Hugs pushes a return address, it pushes both a pointer to the BCO
776 to return to, and a pointer to a static code fragment @HUGS_RET@ (this
777 will be described in Section \ref{sect:ghc-to-hugs-return}). The
778 stack layout is shown in Figure \ref{fig:hugs-return-stack}.
782 \input{hugs_ret.pstex_t}
784 \caption{Stack layout for a hugs return address}
785 \label{fig:hugs-return-stack}
790 \input{hugs_ret2.pstex_t}
792 \caption{Stack layout on enterings a hugs return address}
793 \label{fig:hugs-return2}
796 When a Hugs byte-code sequence is returning, it first places the
797 return value on the stack. It then examines the return address (now
798 the second word on the stack):
802 \item If the return address is @HUGS_RET@, rearrange the stack so that
803 it has the returned object followed by the pointer to the BCO at the
804 top, then enter the BCO (Figure \ref{fig:hugs-return2}).
806 \item If the top of the stack is not @HUGS_RET@, we need to do a world
807 switch as described in Section \ref{sect:hugs-to-ghc-return}.
812 \section{The Scheduler}
814 The Scheduler is the heart of the run-time system. A running program
815 consists of a single running thread, and a list of runnable and
816 blocked threads. The running thread returns to the scheduler when any
817 of the following conditions arises:
820 \item A heap check fails, and a garbage collection is required
821 \item Compiled code needs to switch to interpreted code, and vice
823 \item The thread becomes blocked.
824 \item The thread is preempted.
827 A running system has a global state, consisting of
830 \item @Hp@, the current heap pointer, which points to the next
831 available address in the Heap.
832 \item @HpLim@, the heap limit pointer, which points to the end of the
834 \item The Thread Preemption Flag, which is set whenever the currently
835 running thread should be preempted at the next opportunity.
836 \item A list of runnable threads.
837 \item A list of blocked threads.
840 Each thread is represented by a Thread State Object (TSO), which is
841 described in detail in Section \ref{sect:TSO}.
843 The following is pseudo-code for the inner loop of the scheduler
847 while (threads_exist) {
848 // handle global problems: GC, parallelism, etc
850 if (external_message) service_message();
851 // deal with other urgent stuff
853 pick a runnable thread;
855 switch (thread->whatNext) {
856 case (RunGHC pc): status=runGHC(pc); break;
857 case (RunHugs bc): status=runHugs(bc); break;
859 switch (status) { // handle local problems
860 case (StackOverflow): enlargeStack; break;
861 case (Error e) : error(thread,e); break;
862 case (ExitWith e) : exit(e); break;
863 case (Yield) : break;
865 } while (thread_runnable);
869 Optimisations to avoid excess trampolining from Hugs into itself.
870 How do we invoke GC, ccalls, etc.
871 General ccall (@ccall-GC@) and optimised ccall.
873 \section{Switching Worlds}
875 \label{sect:switching-worlds}
877 Because this is a combined compiled/interpreted system, the
878 interpreter will sometimes encounter compiled code, and vice-versa.
880 All world-switches go via the scheduler, ensuring that the world is in
881 a known state ready to enter either compiled code or the interpreter.
882 When a thread is run from the scheduler, the @whatNext@ field in the
883 TSO (Section \ref{sect:TSO}) is checked to find out how to execute the
887 \item If @whatNext@ is set to @ReturnGHC@, we load up the required
888 registers from the TSO and jump to the address at the top of the user
890 \item If @whatNext@ is set to @EnterGHC@, we load up the required
891 registers from the TSO and enter the closure pointed to by the top
893 \item If @whatNext@ is set to @EnterHugs@, we enter the top thing on
894 the stack, using the interpreter.
897 There are four cases we need to consider:
900 \item A GHC thread enters a Hugs-built closure.
901 \item A GHC thread returns to a Hugs-compiled return address.
902 \item A Hugs thread enters a GHC-built closure.
903 \item A Hugs thread returns to a Hugs-compiled return address.
906 GHC-compiled modules cannot call functions in a Hugs-compiled module
907 directly, because the compiler has no information about arities in the
908 external module. Therefore it must assume any top-level objects are
909 CAFs, and enter their closures.
911 \ToDo{dynamic linking stuff}
912 \ToDo{Hugs-built constructors?}
914 We now examine the various cases one by one and describe how the
915 switch happens in each situation.
917 \subsection{A GHC thread enters a Hugs-built closure}
918 \label{sect:ghc-to-hugs-closure}
920 There are three possibilities: GHC has entered the BCO directly (for a
921 top-level function closure), it has entered a @HUGS_AP@, or it has
922 entered a @HUGS_PAP@.
924 The code for all three objects is the same:
927 \item Push the address of the object entered on the stack.
928 \item Save the current state of the thread in its TSO.
929 \item Return to the scheduler, setting @whatNext@ to @EnterHugs@.
932 \subsection{A GHC thread returns to a Hugs-compiled return address}
933 \label{sect:ghc-to-hugs-return}
935 Hugs return addresses are laid out as in Figure
936 \ref{fig:hugs-return-stack}. If GHC is returning, it will return to
937 the address at the top of the stack, namely @HUGS_RET@. The code at
938 @HUGS_RET@ performs the following:
941 \item pushes \Arg{1} (the return value) on the stack.
942 \item saves the thread state in the TSO
943 \item returns to the scheduler with @whatNext@ set to @EnterHugs@.
946 \noindent When Hugs runs, it will enter the return value, which will
947 return using the correct Hugs convention (Section
948 \ref{sect:hugs-return-convention}) to the return address underneath it
951 \subsection{A Hugs thread enters a GHC-compiled closure}
952 \label{sect:hugs-to-ghc-closure}
954 Hugs can recognise a GHC-built closure as not being one of the
955 following types of object:
961 \item An indirection, or
965 When Hugs is called on to enter a GHC closure, it executes the
966 following sequence of instructions:
969 \item Push the address of the closure on the stack.
970 \item Save the current state of the thread in the TSO.
971 \item Return to the scheduler, with the @whatNext@ field set to
975 \subsection{A Hugs thread returns to a GHC-compiled return address}
976 \label{sect:hugs-to-ghc-return}
978 When hugs encounters a return address on the stack that is not
979 @HUGS_RET@, it knows that a world-switch is required. At this point
980 the stack contains a pointer to the return value, followed by the GHC
981 return address. The following sequence is then performed:
984 \item save the state of the thread in the TSO.
985 \item return to the scheduler, setting @whatNext@ to @EnterGHC@.
988 The first thing that GHC will do is enter the object on the top of the
989 stack, which is a pointer to the return value. This value will then
990 return itself to the return address using the GHC return convention.
992 \part{Implementation}
993 \section{Heap objects}
994 \label{sect:fixed-header}
996 \ToDo{Fix this picture}
1006 Every {\em heap object}, or {\em closure} is a contiguous block
1007 of memory, consisting of a fixed-format {\em header} followed
1008 by zero or more {\em data words}.
1009 The header consists of
1010 the following fields:
1012 \item A one-word {\em info pointer}, which points to
1013 the object's static {\em info table}.
1014 \item Zero or more {\em admin words} that support
1016 \item Profiling (notably a {\em cost centre} word).
1017 \note{We could possibly omit the cost centre word from some
1018 administrative objects.}
1019 \item Parallelism (e.g. GranSim keeps the object's global address here,
1020 though GUM keeps a separate hash table).
1021 \item Statistics (e.g. a word to track how many times a thunk is entered.).
1023 We add a Ticky word to the fixed-header part of closures. This is
1024 used to indicate if a closure has been updated but not yet entered. It
1025 is set when the closure is updated and cleared when subsequently
1028 NB: It is {\em not} an ``entry count'', it is an
1029 ``entries-after-update count.'' The commoning up of @CONST@,
1030 @CHARLIKE@ and @INTLIKE@ closures is turned off(?) if this is
1031 required. This has only been done for 2s collection.
1036 Most of the RTS is completely insensitive to the number of admin words.
1037 The total size of the fixed header is @FIXED_HS@.
1039 Many heap objects contain fields allowing them to be inserted onto lists
1040 during evaluation or during garbage collection. The lists required by
1041 the evaluator and storage manager are as follows.
1044 \item 2 lists of threads: runnable threads and sleeping threads.
1046 \item The {\em static object list} is a list of all statically
1047 allocated objects which might contain pointers into the heap.
1048 (Section~\ref{sect:static-objects}.)
1050 \item The {\em updated thunk list} is a list of all thunks in the old
1051 generation which have been updated with an indirection.
1052 (Section~\ref{sect:IND_OLDGEN}.)
1054 \item The {\em mutables list} is a list of all other objects in the
1055 old generation which might contain pointers into the new generation.
1056 Most of the object on this list are ``mutable.''
1057 (Section~\ref{sect:mutables}.)
1059 \item The {\em Foreign Object list} is a list of all foreign objects
1060 which have not yet been deallocated. (Section~\ref{sect:FOREIGN}.)
1062 \item The {\em Spark pool} is a doubly(?) linked list of Spark objects
1063 maintained by the parallel system. (Section~\ref{sect:SPARK}.)
1065 \item The {\em Blocked Fetch list} (or
1066 lists?). (Section~\ref{sect:BLOCKED_FETCH}.)
1068 \item For each thread, there is a list of all update frames on the
1069 stack. (Section~\ref{sect:data-updates}.)
1074 \ToDo{The links for these fields are usually inserted immediately
1075 after the fixed header except ...}
1077 \subsection{Info Tables}
1079 An {\em info table} is a contiguous block of memory, {\em laid out
1080 backwards}. That is, the first field in the list that follows
1081 occupies the highest memory address, and the successive fields occupy
1082 successive decreasing memory addresses.
1085 \begin{tabular}{|c|}
1086 \hline Parallelism Info
1087 \\ \hline Profile Info
1088 \\ \hline Debug Info
1089 \\ \hline Tag / Static reference table
1090 \\ \hline Storage manager layout info
1091 \\ \hline Closure type
1092 \\ \hline entry code
1096 An info table has the following contents (working backwards in memory
1099 \item The {\em entry code} for the closure.
1100 This code appears literally as the (large) last entry in the
1101 info table, immediately preceded by the rest of the info table.
1102 An {\em info pointer} always points to the first byte of the entry code.
1104 \item A one-word {\em closure type field}, @INFO_TYPE@, identifies what kind
1105 of closure the object is. The various types of closure are described
1106 in Section~\ref{sect:closures}.
1107 In some configurations, some useful properties of
1108 closures (is it a HNF? can it be sparked?)
1109 are represented as high-order bits so they can be tested quickly.
1111 \item A single pointer or word --- the {\em storage manager info field},
1112 @INFO_SM@, contains auxiliary information describing the closure's
1113 precise layout, for the benefit of the garbage collector and the code
1114 that stuffs graph into packets for transmission over the network.
1116 \item A one-word {\em Tag/Static Reference Table} field, @INFO_SRT@.
1117 For data constructors, this field contains the constructor tag, in the
1118 range $0..n-1$ where $n$ is the number of constructors. For all other
1119 objects it contains a pointer to a table which enables the garbage
1120 collector to identify all accessible code and CAFs. They are fully
1121 described in Section~\ref{sect:srt}.
1123 \item {\em Profiling info\/}
1125 Closure category records are attached to the info table of the
1126 closure. They are declared with the info table. We put pointers to
1127 these ClCat things in info tables. We need these ClCat things because
1128 they are mutable, whereas info tables are immutable. Hashing will map
1129 similar categories to the same hash value allowing statistics to be
1130 grouped by closure category.
1132 Cost Centres and Closure Categories are hashed to provide indexes
1133 against which arbitrary information can be stored. These indexes are
1134 memoised in the appropriate cost centre or category record and
1135 subsequent hashes avoided by the index routine (it simply returns the
1138 There are different features which can be hashed allowing information
1139 to be stored for different groupings. Cost centres have the cost
1140 centre recorded (using the pointer), module and group. Closure
1141 categories have the closure description and the type
1142 description. Records with the same feature will be hashed to the same
1145 The initialisation routines, @init_index_<feature>@, allocate a hash
1146 table in which the cost centre / category records are stored. The
1147 lower bound for the table size is taken from @max_<feature>_no@. They
1148 return the actual table size used (the next power of 2). Unused
1149 locations in the hash table are indicated by a 0 entry. Successive
1150 @init_index_<feature>@ calls just return the actual table size.
1152 Calls to @index_<feature>@ will insert the cost centre / category
1153 record in the @<feature>@ hash table, if not already inserted. The hash
1154 index is memoised in the record and returned.
1156 CURRENTLY ONLY ONE MEMOISATION SLOT IS AVILABLE IN EACH RECORD SO
1157 HASHING CAN ONLY BE DONE ON ONE FEATURE FOR EACH RECORD. This can be
1158 easily relaxed at the expense of extra memoisation space or continued
1161 The initialisation routines must be called before initialisation of
1162 the stacks and heap as they require to allocate storage. It is also
1163 expected that the caller may want to allocate additional storage in
1164 which to store profiling information based on the return table size
1168 \begin{tabular}{|l|}
1172 \\ \hline Description String
1173 \\ \hline Type String
1179 \item[Hash Index] Memoised copy
1181 Is this category selected (-1 == not memoised, selected? 0 or 1)
1183 One of the following values (defined in CostCentre.lh):
1191 A partial application.
1193 A thunk, or suspension.
1198 \item[@ForeignObj_K@]
1199 A Foreign object (non-Haskell heap resident).
1201 The Stable Pointer table. (There should only be one of these but it
1202 represents a form of weak space leak since it can't shrink to meet
1203 non-demand so it may be worth watching separately? ADR)
1204 \item[@INTERNAL_KIND@]
1205 Something internal to the runtime system.
1209 \item[Description] Source derived string detailing closure description.
1210 \item[Type] Source derived string detailing closure type.
1213 \item {\em Parallelism info\/}
1216 \item {\em Debugging info\/}
1222 %-----------------------------------------------------------------------------
1223 \subsection{Kinds of Heap Object}
1224 \label{sect:closures}
1226 Heap objects can be classified in several ways, but one useful one is
1230 {\em Static closures} occupy fixed, statically-allocated memory
1231 locations, with globally known addresses.
1234 {\em Dynamic closures} are individually allocated in the heap.
1237 {\em Stack closures} are closures allocated within a thread's stack
1238 (which is itself a heap object). Unlike other closures, there are
1239 never any pointers to stack closures. Stack closures are discussed in
1240 Section~\ref{sect:stacks}.
1243 A second useful classification is this:
1246 {\em Executive closures}, such as thunks and data constructors,
1247 participate directly in a program's execution. They can be subdivided into
1248 two kinds of objects according to their type:
1251 {\em Pointed objects}, represent values of a {\em pointed} type
1252 (<.pointed types launchbury.>) --i.e.~a type that includes $\bottom$ such as @Int@ or @Int# -> Int#@.
1254 \item {\em Unpointed objects}, represent values of a {\em unpointed} type --i.e.~a type that does not include $\bottom$ such as @Int#@ or @Array#@.
1256 \item {\em Activation frames}, represent ``continuations''. They are
1257 always stored on the stack and are never pointed to by heap objects or
1258 passed as arguments. \note{It's not clear if this will still be true
1259 once we support speculative evaluation.}
1263 \item {\em Administrative closures}, such as stack objects and thread
1264 state objects, do not represent values in the original program.
1267 Only pointed objects can be entered. All pointed objects share a
1268 common header format: the ``pointed header''; while all unpointed
1269 objects share a common header format: the ``unpointed header''.
1270 \ToDo{Describe the difference and update the diagrams to mention
1271 an appropriate header type.}
1273 This section enumerates all the kinds of heap objects in the system.
1274 Each is identified by a distinct @INFO_TYPE@ tag in its info table.
1276 \ToDo{Check this table very carefully}
1278 \begin{tabular}{|l|l|l|l|l|l|l|l|l|l|l|}
1281 closure kind & HNF & UPD & NS & STA & THU & MUT & UPT & BH & IND & Section \\
1287 @CONSTR@ & 1 & & 1 & & & & & & & \ref{sect:CONSTR} \\
1288 @CONSTR_STATIC@ & 1 & & 1 & 1 & & & & & & \ref{sect:CONSTR} \\
1289 @CONSTR_STATIC_NOCAF@ & 1 & & 1 & 1 & & & & & & \ref{sect:CONSTR} \\
1291 @FUN@ & 1 & & ? & & & & & & & \ref{sect:FUN} \\
1292 @FUN_STATIC@ & 1 & & ? & 1 & & & & & & \ref{sect:FUN} \\
1294 @THUNK@ & & 1 & & & 1 & & & & & \ref{sect:THUNK} \\
1295 @THUNK_STATIC@ & & 1 & & 1 & 1 & & & & & \ref{sect:THUNK} \\
1296 @THUNK_SELECTOR@ & & 1 & 1 & & 1 & & & & & \ref{sect:THUNK_SEL} \\
1298 @BCO@ & 1 & & 1 & & & & & & & \ref{sect:BCO} \\
1299 @BCO_CAF@ & & 1 & & & 1 & & & & & \ref{sect:BCO} \\
1301 @HUGS_AP@ & & 1 & & & 1 & & & & & \ref{sect:HUGS-AP} \\
1302 @HUGS_PAP@ & & & 1 & & & & & & & \ref{sect:HUGS-AP} \\
1304 @PAP@ & 1 & & 1 & & & & & & & \ref{sect:PAP} \\
1306 @IND@ & ? & & ? & & ? & & & & 1 & \ref{sect:IND} \\
1307 @IND_OLDGEN@ & ? & & ? & & ? & & & & 1 & \ref{sect:IND} \\
1308 @IND_PERM@ & ? & & ? & & ? & & & & 1 & \ref{sect:IND} \\
1309 @IND_OLDGEN_PERM@ & ? & & ? & & ? & & & & 1 & \ref{sect:IND} \\
1310 @IND_STATIC@ & ? & & ? & 1 & ? & & & & 1 & \ref{sect:IND} \\
1317 @ARR_WORDS@ & 1 & & 1 & & & & 1 & & & \ref{sect:ARR_WORDS1},\ref{sect:ARR_WORDS2} \\
1318 @ARR_PTRS@ & 1 & & 1 & & & & 1 & & & \ref{sect:ARR_PTRS} \\
1319 @MUTVAR@ & 1 & & 1 & & & 1 & 1 & & & \ref{sect:MUTVAR} \\
1320 @MUTARR_PTRS@ & 1 & & 1 & & & 1 & 1 & & & \ref{sect:MUTARR_PTRS} \\
1321 @MUTARR_PTRS_FROZEN@ & 1 & & 1 & & & 1 & 1 & & & \ref{sect:MUTARR_PTRS_FROZEN} \\
1323 @FOREIGN@ & 1 & & 1 & & & & 1 & & & \ref{sect:FOREIGN} \\
1325 @BH@ & & 1 & 1 & & ? & ? & & 1 & ? & \ref{sect:BH} \\
1326 @MVAR@ & 1 & & 1 & & & & & & & \ref{sect:MVAR} \\
1327 @IVAR@ & 1 & & 1 & & & & & & & \ref{sect:IVAR} \\
1328 @FETCHME@ & 1 & & 1 & & & & & & & \ref{sect:FETCHME} \\
1332 Activation frames do not live (directly) on the heap --- but they have
1333 a similar organisation. The classification bits are all zero in
1336 \begin{tabular}{|l|l|}\hline
1337 closure kind & Section \\ \hline
1338 @RET_SMALL@ & \ref{sect:activation-records} \\
1339 @RET_VEC_SMALL@ & \ref{sect:activation-records} \\
1340 @RET_BIG@ & \ref{sect:activation-records} \\
1341 @RET_VEC_BIG@ & \ref{sect:activation-records} \\
1342 @UPDATE_FRAME@ & \ref{sect:activation-records} \\
1346 There are also a number of administrative objects. The classification bits are
1347 all zero in administrative objects.
1349 \begin{tabular}{|l|l|}\hline
1350 closure kind & Section \\ \hline
1351 @TSO@ & \ref{sect:TSO} \\
1352 @STACK_OBJECT@ & \ref{sect:STACK_OBJECT} \\
1353 @STABLEPTR_TABLE@ & \ref{sect:STABLEPTR_TABLE} \\
1354 @SPARK_OBJECT@ & \ref{sect:SPARK} \\
1355 @BLOCKED_FETCH@ & \ref{sect:BLOCKED_FETCH} \\
1359 \ToDo{I guess the parallel system has something like a stable ptr
1360 table. Is there any opportunity for sharing code/data structures
1364 \subsection{Classification bits}
1366 The top bits of the @INFO_TYPE@ tag tells what sort of animal the
1369 \begin{tabular}{|l|l|l|} \hline
1370 Abbrev & Bit & Interpretation \\ \hline
1371 HNF & 0 & 1 $\Rightarrow$ Head normal form \\
1372 UPD & 4 & 1 $\Rightarrow$ May be updated (inconsistent with being a HNF) \\
1373 NS & 1 & 1 $\Rightarrow$ Don't spark me (Any HNF will have this set to 1)\\
1374 STA & 2 & 1 $\Rightarrow$ This is a static closure \\
1375 THU & 8 & 1 $\Rightarrow$ Is a thunk \\
1376 MUT & 3 & 1 $\Rightarrow$ Has mutable pointer fields \\
1377 UPT & 5 & 1 $\Rightarrow$ Has an unpointed type (eg a primitive array) \\
1378 BH & 6 & 1 $\Rightarrow$ Is a black hole \\
1379 IND & 7 & 1 $\Rightarrow$ Is an indirection \\
1383 Updatable structures (@_UP@) are thunks that may be shared. Primitive
1384 arrays (@_BM@ -- Big Mothers) are structures that are always held
1385 in-memory (basically extensions of a closure). Because there may be
1386 offsets into these arrays, a primitive array cannot be handled as a
1387 FetchMe in the parallel system, but must be shipped in its entirety if
1388 its parent closure is shipped.
1390 The other bits in the info-type field simply give a unique bit-pattern
1391 to identify the closure type.
1395 #define _NF 0x0001 /* Normal form */
1396 #define _NS 0x0002 /* Don't spark */
1397 #define _ST 0x0004 /* Is static */
1398 #define _MU 0x0008 /* Is mutable */
1399 #define _UP 0x0010 /* Is updatable (but not mutable) */
1400 #define _BM 0x0020 /* Is a "primitive" array */
1401 #define _BH 0x0040 /* Is a black hole */
1402 #define _IN 0x0080 /* Is an indirection */
1403 #define _TH 0x0100 /* Is a thunk */
1408 SPEC_N SPEC | _NF | _NS
1410 SPEC_U SPEC | _UP | _TH
1413 GEN_N GEN | _NF | _NS
1415 GEN_U GEN | _UP | _TH
1418 TUPLE _NF | _NS | _BM
1419 DATA _NF | _NS | _BM
1420 MUTUPLE _NF | _NS | _MU | _BM
1421 IMMUTUPLE _NF | _NS | _BM
1433 CAF _NF | _NS | _ST | _IN
1442 STKO_DYNAMIC STKO | _MU
1443 STKO_STATIC STKO | _ST
1445 SPEC_RBH _NS | _MU | _BH
1446 GEN_RBH _NS | _MU | _BH
1455 An indirection either points to HNF (post update); or is result of
1456 overwriting a FetchMe, in which case the thing fetched is either
1457 under evaluation (BH), or by now an HNF. Thus, indirections get NoSpark flag.
1461 \subsection{Hugs Objects}
1463 \subsubsection{Byte-Code Objects}
1466 A Byte-Code Object (BCO) is a container for a a chunk of byte-code,
1467 which can be executed by Hugs. The byte-code represents a
1468 supercombinator in the program: when hugs compiles a module, it
1469 performs lambda lifting and each resulting supercombinator becomes a
1470 byte-code object in the heap.
1472 There are two kinds of BCO: a standard @BCO@ which has an arity of one
1473 or more, and a @BCO_CAF@ which takes no arguments and can be updated.
1474 When a @BCO_CAF@ is updated, the code is thrown away!
1476 The semantics of BCOs are described in Section
1477 \ref{sect:hugs-heap-objects}. A BCO has the following structure:
1480 \begin{tabular}{|l|l|l|l|l|l|}
1482 \emph{Fixed Header} & \emph{Layout} & \emph{Offset} & \emph{Size} &
1483 \emph{Literals} & \emph{Byte code} \\
1490 \item The entry code is a static code fragment/info table that
1491 returns to the scheduler to invoke Hugs (Section
1492 \ref{sect:ghc-to-hugs-closure}).
1493 \item \emph{Layout} contains the number of pointer literals in the
1494 \emph{Literals} field.
1495 \item \emph{Offset} is the offset to the byte code from the start of
1497 \item \emph{Size} is the number of words of byte code in the object.
1498 \item \emph{Literals} contains any pointer and non-pointer literals used in
1499 the byte-codes (including jump addresses), pointers first.
1500 \item \emph{Byte code} contains \emph{Size} words of non-pointer byte
1504 \subsubsection{@HUGS_AP@ objects}
1505 \label{sect:HUGS-AP}
1507 There are two kinds of @HUGS_AP@ objects: a standard @HUGS_AP@, used
1508 to represent thunks buit by Hugs, and a @HUGS_PAP@, used for partial
1509 applications. The only difference between the two is that a
1510 @HUGS_PAP@ is non-updatable.
1513 \begin{tabular}{|l|l|l|l|}
1515 \emph{Fixed Header} & \emph{BCO} & \emph{Layout} & \emph{Free Variables} \\
1524 \item The entry code is a statically-compiled code fragment/info table
1525 that returns to the scheduler to invoke Hugs (Sections
1526 \ref{sect:ghc-to-hugs-closure}, \ref{sect:ghc-to-hugs-return}).
1528 \item \emph{BCO} is a pointer to the BCO for the thunk.
1530 \item \emph{Layout} contains the number of pointers and the size of
1531 the \emph{Free Variables} field.
1533 \item \emph{Free Variables} contains the free variables of the
1534 thunk/partial application/return address, pointers first.
1538 \subsection{Pointed Objects}
1540 All pointed objects can be entered.
1542 \subsubsection{Function closures}\label{sect:FUN}
1544 Function closures represent lambda abstractions. For example,
1545 consider the top-level declaration:
1547 f = \x -> let g = \y -> x+y
1550 Both @f@ and @g@ are represented by function closures. The closure
1551 for @f@ is {\em static} while that for @g@ is {\em dynamic}.
1553 The layout of a function closure is as follows:
1555 \begin{tabular}{|l|l|l|l|}\hline
1556 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} \\ \hline
1559 The data words (pointers and non-pointers) are the free variables of
1560 the function closure.
1561 The number of pointers
1562 and number of non-pointers are stored in the @INFO_SM@ word, in the least significant
1563 and most significant half-word respectively.
1565 There are several different sorts of function closure, distinguished
1566 by their @INFO_TYPE@ field:
1568 \item @FUN@: a vanilla, dynamically allocated on the heap.
1570 \item $@FUN_@p@_@np$: to speed up garbage collection a number of
1571 specialised forms of @FUN@ are provided, for particular $(p,np)$ pairs,
1572 where $p$ is the number of pointers and $np$ the number of non-pointers.
1574 \item @FUN_STATIC@. Top-level, static, function closures (such as
1575 @f@ above) have a different
1576 layout than dynamic ones:
1578 \begin{tabular}{|l|l|l|}\hline
1579 {\em Fixed header} & {\em Static object link} \\ \hline
1582 Static function closures have no free variables. (However they may refer to other
1583 static closures; these references are recorded in the function closure's SRT.)
1584 They have one field that is not present in dynamic closures, the {\em static object
1585 link} field. This is used by the garbage collector in the same way that to-space
1586 is, to gather closures that have been determined to be live but that have not yet
1588 \note{Static function closures that have no static references, and hence
1589 a null SRT pointer, don't need the static object link field. Is it worth
1590 taking advantage of this? See @CONSTR_STATIC_NOCAF@.}
1593 Each lambda abstraction, $f$, in the STG program has its own private info table.
1594 The following labels are relevant:
1596 \item $f$@_info@ is $f$'s info table.
1597 \item $f$@_entry@ is $f$'s slow entry point (i.e. the entry code of its
1598 info table; so it will label the same byte as $f$@_info@).
1599 \item $f@_fast_@k$ is $f$'s fast entry point. $k$ is the number of arguments
1600 $f$ takes; encoding this number in the fast-entry label occasionally catches some nasty
1601 code-generation errors.
1604 \subsubsection{Data Constructors}\label{sect:CONSTR}
1606 Data-constructor closures represent values constructed with
1607 algebraic data type constructors.
1608 The general layout of data constructors is the same as that for function
1611 \begin{tabular}{|l|l|l|l|}\hline
1612 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} \\ \hline
1616 The SRT pointer in a data constructor's info table is used for the
1617 constructor tag, since a constructor never has any static references.
1619 There are several different sorts of constructor:
1621 \item @CONSTR@: a vanilla, dynamically allocated constructor.
1622 \item @CONSTR_@$p$@_@$np$: just like $@FUN_@p@_@np$.
1623 \item @CONSTR_INTLIKE@.
1624 A dynamically-allocated heap object that looks just like an @Int@. The
1625 garbage collector checks to see if it can common it up with one of a fixed
1626 set of static int-like closures, thus getting it out of the dynamic heap
1629 \item @CONSTR_CHARLIKE@: same deal, but for @Char@.
1631 \item @CONSTR_STATIC@ is similar to @FUN_STATIC@, with the complication that
1632 the layout of the constructor must mimic that of a dynamic constructor,
1633 because a static constructor might be returned to some code that unpacks it.
1634 So its layout is like this:
1636 \begin{tabular}{|l|l|l|l|l|}\hline
1637 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} & {\em Static object link}\\ \hline
1640 The static object link, at the end of the closure, serves the same purpose
1641 as that for @FUN_STATIC@. The pointers in the static constructor can point
1642 only to other static closures.
1644 The static object link occurs last in the closure so that static
1645 constructors can store their data fields in exactly the same place as
1646 dynamic constructors.
1648 \item @CONSTR_STATIC_NOCAF@. A statically allocated data constructor
1649 that guarantees not to point (directly or indirectly) to any CAF
1650 (section~\ref{sect:CAF}). This means it does not need a static object
1651 link field. Since we expect that there might be quite a lot of static
1652 constructors this optimisation makes sense. Furthermore, the @NOCAF@
1653 tag allows the compiler to indicate that no CAFs can be reached
1654 anywhere {\em even indirectly}.
1659 For each data constructor $Con$, two
1660 info tables are generated:
1662 \item $Con$@_info@ labels $Con$'s dynamic info table,
1663 shared by all dynamic instances of the constructor.
1664 \item $Con$@_static@ labels $Con$'s static info table,
1665 shared by all static instances of the constructor.
1668 \subsubsection{Thunks}
1670 \label{sect:THUNK_SEL}
1672 A thunk represents an expression that is not obviously in head normal
1673 form. For example, consider the following top-level definitions:
1675 range = between 1 10
1676 f = \x -> let ys = take x range
1679 Here the right-hand sides of @range@ and @ys@ are both thunks; the former
1680 is static while the latter is dynamic.
1682 The layout of a thunk is the same as that for a function closure,
1683 except that it may have some words of ``slop'' at the end to make sure
1685 at least @MIN_UPD_PAYLOAD@ words in addition to its
1688 \begin{tabular}{|l|l|l|l|l|}\hline
1689 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} & {\em Slop} \\ \hline
1692 The @INFO_SM@ word contains the same information as for function
1693 closures; that is, number of pointers and number of non-pointers (excluding slop).
1695 A thunk differs from a function closure in that it can be updated.
1697 There are several forms of thunk:
1699 \item @THUNK@: a vanilla, dynamically allocated thunk.
1700 The garbage collection code for thunks whose
1701 pointer + non-pointer words is less than @MIN_UPD_PAYLOAD@ differs from
1702 that for function closures and data constructors, because the GC code
1703 has to account for the slop.
1704 \item $@THUNK_@p@_@np$. Similar comments apply.
1705 \item @THUNK_STATIC@. A static thunk is also known as
1706 a {\em constant applicative form}, or {\em CAF}.
1709 \begin{tabular}{|l|l|l|l|l|}\hline
1710 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} & {\em Slop} & {\em Static object link}\\ \hline
1714 \item @THUNK_SELECTOR@ is a (dynamically allocated) thunk
1715 whose entry code performs a simple selection operation from
1716 a data constructor drawn from a single-constructor type. For example,
1719 x = case y of (a,b) -> a
1721 is a selector thunk. A selector thunk is laid out like this:
1723 \begin{tabular}{|l|l|l|l|}\hline
1724 {\em Fixed header} & {\em Selectee pointer} \\ \hline
1727 The @INFO_SM@ word contains the byte offset of the desired word in
1728 the selectee. Note that this is different from all other thunks.
1730 The garbage collector ``peeks'' at the selectee's
1731 tag (in its info table). If it is evaluated, then it goes ahead and do
1732 the selection, and then behaves just as if the selector thunk was an
1733 indirection to the selected field.
1735 evaluated, it treats the selector thunk like any other thunk of that
1736 shape. [Implementation notes.
1737 Copying: only the evacuate routine needs to be special.
1738 Compacting: only the PRStart (marking) routine needs to be special.]
1742 The only label associated with a thunk is its info table:
1744 \item[$f$@_info@] is $f$'s info table.
1748 \subsubsection{Partial applications (PAPs)}\label{sect:PAP}
1750 A partial application (PAP) represents a function applied to too few arguments.
1751 It is only built as a result of updating after an argument-satisfaction
1752 check failure. A PAP has the following shape:
1754 \begin{tabular}{|l|l|l|l|}\hline
1755 {\em Fixed header} & {\em No of arg words} & {\em Function closure} & {\em Arg stack} \\ \hline
1758 The ``arg stack'' is a copy of of the chunk of stack above the update
1759 frame; ``no of arg words'' tells how many words it consists of. The
1760 function closure is (a pointer to) the closure for the function whose
1761 argument-satisfaction check failed.
1763 There is just one standard form of PAP with @INFO_TYPE@ = @PAP@.
1764 There is just one info table too, called @PAP_info@.
1765 Its entry code simply copies the arg stack chunk back on top of the
1766 stack and enters the function closure. (It has to do a stack overflow test first.)
1768 There are no static PAPs.
1770 \subsubsection{Indirections}
1772 \label{sect:IND_OLDGEN}
1774 Indirection closures just point to other closures. They are introduced
1775 when a thunk is updated to point to its value.
1776 The entry code for all indirections simply enters the closure it points to.
1778 There are several forms of indirection:
1780 \item[@IND@] is the vanilla, dynamically-allocated indirection.
1781 It is removed by the garbage collector. It has the following
1784 \begin{tabular}{|l|l|l|}\hline
1785 {\em Fixed header} & {\em Target closure} \\ \hline
1789 \item[@IND_OLDGEN@] is the indirection used to update an old-generation
1790 thunk. Its shape is like this:
1792 \begin{tabular}{|l|l|l|}\hline
1793 {\em Fixed header} & {\em Mutable link field} & {\em Target closure} \\ \hline
1796 It contains a {\em mutable link field} that is used to string together
1797 all old-generation indirections that might have a pointer into
1801 \item[@IND_PERMANENT@ and @IND_OLDGEN_PERMANENT@.]
1802 for lexical profiling, it is necessary to maintain cost centre
1803 information in an indirection, so ``permanent indirections'' are
1804 retained forever. Otherwise they are just like vanilla indirections.
1805 \note{If a permanent indirection points to another permanent
1806 indirection or a @CONST@ closure, it is possible to elide the indirection
1807 since it will have no effect on the profiler.}
1808 \note{Do we still need @IND@ and @IND_OLDGEN@
1809 in the profiling build, or can we just make
1810 do with one pair whose behaviour changes when profiling is built?}
1812 \item[@IND_STATIC@] is used for overwriting CAFs when they have been
1813 evaluated. Static indirections are not removed by the garbage
1814 collector; and are statically allocated outside the heap (and should
1815 stay there). Their static object link field is used just as for
1816 @FUN_STATIC@ closures.
1819 \begin{tabular}{|l|l|l|}
1821 {\em Fixed header} & {\em Target closure} & {\em Static object link} \\
1828 \subsubsection{Activation Records}
1830 Activation records are parts of the stack described by return address
1831 info tables (closures with @INFO_TYPE@ values of @RET_SMALL@,
1832 @RET_VEC_SMALL@, @RET_BIG@ and @RET_VEC_BIG@). They are described in
1833 section~\ref{sect:activation-records}.
1836 \subsubsection{Black holes, MVars and IVars}
1841 Black hole closures are used to overwrite closures currently being
1842 evaluated. They inform the garbage collector that there are no live
1843 roots in the closure, thus removing a potential space leak.
1845 Black holes also become synchronization points in the threaded world.
1846 They contain a pointer to a list of blocked threads to be awakened
1847 when the black hole is updated (or @NULL@ if the list is empty).
1849 \begin{tabular}{|l|l|l|}
1851 {\em Fixed header} & {\em Mutable link} & {\em Blocked thread link} \\
1855 The {\em Blocked thread link} points to the TSO of the first thread
1856 waiting for the value of this thunk. All subsequent TSOs in the list
1857 are linked together using their @TSO_LINK@ field.
1859 When the blocking queue is non-@NULL@, the black hole must be added to
1860 the mutables list since the TSOs on the list may contain pointers into
1861 the new generation. There is no need to clutter up the mutables list
1862 with black holes with empty blocking queues.
1867 \subsubsection{FetchMes}\label{sect:FETCHME}
1869 In the parallel systems, FetchMes are used to represent pointers into
1870 the global heap. When evaluated, the value they point to is read from
1873 \ToDo{Describe layout}
1876 \subsection{Unpointed Objects}
1878 A variable of unpointed type is always bound to a {\em value}, never to a {\em thunk}.
1879 For this reason, unpointed objects cannot be entered.
1881 A {\em value} may be:
1883 \item {\em Boxed}, i.e.~represented indirectly by a pointer to a heap object (e.g.~foreign objects, arrays); or
1884 \item {\em Unboxed}, i.e.~represented directly by a bit-pattern in one or more registers (e.g.~@Int#@ and @Float#@).
1886 All {\em pointed} values are {\em boxed}.
1888 \subsubsection{Immutable Objects}
1889 \label{sect:ARR_WORDS1}
1890 \label{sect:ARR_PTRS}
1893 \item[@ARR_WORDS@] is a variable-sized object consisting solely of
1894 non-pointers. It is used for arrays of all
1895 sorts of things (bytes, words, floats, doubles... it doesn't matter).
1897 \begin{tabular}{|c|c|c|c|}
1899 {\em Fixed Hdr} & {\em No of non-pointers} & {\em Non-pointers\ldots} \\ \hline
1903 \item[@ARR_PTRS@] is an immutable, variable sized array of pointers.
1905 \begin{tabular}{|c|c|c|c|}
1907 {\em Fixed Hdr} & {\em Mutable link} & {\em No of pointers} & {\em Pointers\ldots} \\ \hline
1910 The mutable link is present so that we can easily freeze and thaw an
1911 array (by changing the header and adding/removing the array to the
1916 \subsubsection{Mutable Objects}
1917 \label{sect:mutables}
1918 \label{sect:ARR_WORDS2}
1920 \label{sect:MUTARR_PTRS}
1921 \label{sect:MUTARR_PTRS_FROZEN}
1923 Some of these objects are {\em mutable}; they represent objects which
1924 are explicitly mutated by Haskell code through the @ST@ monad.
1925 They're not used for thunks which are updated precisely once.
1926 Depending on the garbage collector, mutable closures may contain extra
1927 header information which allows a generational collector to implement
1928 the ``write barrier.''
1932 \item[@ARR_WORDS@] is also used to represent {\em mutable} arrays of
1933 bytes, words, floats, doubles, etc. It's possible to use the same
1934 object type because even generational collectors don't need to
1937 \item[@MUTVAR@] is a mutable variable.
1939 \begin{tabular}{|c|c|c|}
1941 {\em Fixed Hdr} & {\em Mutable link} & {\em Pointer} \\ \hline
1945 \item[@MUTARR_PTRS@] is a mutable array of pointers.
1946 Such an array may be {\em frozen}, becoming an @SM_MUTARR_PTRS_FROZEN@, with a
1947 different info-table.
1949 \begin{tabular}{|c|c|c|c|}
1951 {\em Fixed Hdr} & {\em Mutable link} & {\em No of ptrs} & {\em Pointers\ldots} \\ \hline
1955 \item[@MUTARR_PTRS_FROZEN@] is a frozen @MUTARR_PTRS@ closure.
1956 The garbage collector converts @MUTARR_PTRS_FROZEN@ to @ARR_PTRS@ as it removes them from
1962 \subsubsection{Foreign Objects}\label{sect:FOREIGN}
1964 Here's what a ForeignObj looks like:
1967 \begin{tabular}{|l|l|l|l|}
1969 {\em Fixed header} & {\em Data} & {\em Free Routine} & {\em Foreign object link} \\
1974 The @FreeRoutine@ is a reference to the finalisation routine to call
1975 when the @ForeignObj@ becomes garbage. If @freeForeignObject@ is
1976 called on a Foreign Object, the @FreeRoutine@ is set to zero and the
1977 garbage collector will not attempt to call @FreeRoutine@ when the
1978 object becomes garbage.
1980 The Foreign object link is a link to the next foreign object in the
1981 list. This list is traversed at the end of garbage collection: if an
1982 object is about to be deallocated (e.g.~it was not marked or
1983 evacuated), the free routine is called and the object is deleted from
1987 The remaining objects types are all administrative --- none of them may be entered.
1989 \subsection{Thread State Objects (TSOs)}\label{sect:TSO}
1991 In the multi-threaded system, the state of a suspended thread is
1992 packed up into a Thread State Object (TSO) which contains all the
1993 information needed to restart the thread and for the garbage collector
1994 to find all reachable objects. When a thread is running, it may be
1995 ``unpacked'' into machine registers and various other memory locations
1996 to provide faster access.
1998 Single-threaded systems don't really {\em need\/} TSOs --- but they do
1999 need some way to tell the storage manager about live roots so it is
2000 convenient to use a single TSO to store the mutator state even in
2001 single-threaded systems.
2003 Rather than manage TSOs' alloc/dealloc, etc., in some {\em ad hoc}
2004 way, we instead alloc/dealloc/etc them in the heap; then we can use
2005 all the standard garbage-collection/fetching/flushing/etc machinery on
2006 them. So that's why TSOs are ``heap objects,'' albeit very special
2009 \begin{tabular}{|l|l|}
2010 \hline {\em Fixed header}
2011 \\ \hline @TSO_LINK@
2012 \\ \hline @TSO_WHATNEXT@
2013 \\ \hline @TSO_WHATNEXT_INFO@
2014 \\ \hline @TSO_STACK@
2015 \\ \hline {\em Exception Handlers}
2016 \\ \hline {\em Ticky Info}
2017 \\ \hline {\em Profiling Info}
2018 \\ \hline {\em Parallel Info}
2019 \\ \hline {\em GranSim Info}
2023 The contents of a TSO are:
2026 \item A pointer (@TSO_LINK@) used to maintain a list of threads with a similar
2027 state (e.g.~all runable, all sleeping, all blocked on the same black
2028 hole, all blocked on the same MVar, etc.)
2030 \item A word (@TSO_WHATNEXT@) which is in suspended threads to record
2031 how to awaken it. This typically requires a program counter which is stored
2032 in the pointer @TSO_WHATNEXT_INFO@
2034 \item A pointer (@TSO_STACK@) to the top stack block.
2036 \item Optional information for ``Ticky Ticky'' statistics: @TSO_STK_HWM@ is
2037 the maximum number of words allocated to this thread.
2039 \item Optional information for profiling:
2040 @TSO_CCC@ is the current cost centre.
2042 \item Optional information for parallel execution:
2045 \item The types of threads (@TSO_TYPE@):
2047 \item[@T_MAIN@] Must be executed locally.
2048 \item[@T_REQUIRED@] A required thread -- may be exported.
2049 \item[@T_ADVISORY@] An advisory thread -- may be exported.
2050 \item[@T_FAIL@] A failure thread -- may be exported.
2053 \item I've no idea what else
2057 \item Optional information for GranSim execution:
2074 \item clock (gransim light only)
2078 Here are the various queues for GrAnSim-type events.
2089 \subsection{Other weird objects}
2091 \label{sect:BLOCKED_FETCH}
2094 \item[@BlockedFetch@ heap objects (`closures')] (parallel only)
2096 @BlockedFetch@s are inbound fetch messages blocked on local closures.
2097 They arise as entries in a local blocking queue when a fetch has been
2098 received for a local black hole. When awakened, we look at their
2099 contents to figure out where to send a resume.
2101 A @BlockedFetch@ closure has the form:
2103 \begin{tabular}{|l|l|l|l|l|l|}\hline
2104 {\em Fixed header} & link & node & gtid & slot & weight \\ \hline
2108 \item[Spark Closures] (parallel only)
2110 Spark closures are used to link together all closures in the spark pool. When
2111 the current processor is idle, it may choose to speculatively evaluate some of
2112 the closures in the pool. It may also choose to delete sparks from the pool.
2114 \begin{tabular}{|l|l|l|l|l|l|}\hline
2115 {\em Fixed header} & {\em Spark pool link} & {\em Sparked closure} \\ \hline
2123 \subsection{Stack Objects}
2124 \label{sect:STACK_OBJECT}
2127 These are ``stack objects,'' which are used in the threaded world as
2128 the stack for each thread is allocated from the heap in smallish
2129 chunks. (The stack in the sequential world is allocated outside of
2132 Each reduction thread has to have its own stack space. As there may
2133 be many such threads, and as any given one may need quite a big stack,
2134 a naive give-'em-a-big-stack-and-let-'em-run approach will cost a {\em
2137 Our approach is to give a thread a small stack space, and then link
2138 on/off extra ``chunks'' as the need arises. Again, this is a
2139 storage-management problem, and, yet again, we choose to graft the
2140 whole business onto the existing heap-management machinery. So stack
2141 objects will live in the heap, be garbage collected, etc., etc..
2143 A stack object is laid out like this:
2146 \begin{tabular}{|l|}
2150 {\em Link to next stack object (0 for last)}
2152 {\em N, the payload size in words}
2154 {\em @Sp@ (byte offset from head of object)}
2156 {\em @Su@ (byte offset from head of object)}
2158 {\em Payload (N words)}
2163 \ToDo{Are stack objects on the mutable list?}
2165 The stack grows downwards, towards decreasing
2166 addresses. This makes it easier to print out the stack
2167 when debugging, and it means that a return address is
2168 at the lowest address of the chunk of stack it ``knows about''
2169 just like an info pointer on a closure.
2171 The garbage collector needs to be able to find all the
2172 pointers in a stack. How does it do this?
2176 \item Within the stack there are return addresses, pushed
2177 by @case@ expressions. Below a return address (i.e. at higher
2178 memory addresses, since the stack grows downwards) is a chunk
2179 of stack that the return address ``knows about'', namely the
2180 activation record of the currently running function.
2182 \item Below each such activation record is a {\em pending-argument
2183 section}, a chunk of
2184 zero or more words that are the arguments to which the result
2185 of the function should be applied. The return address does not
2187 ``know'' how many pending arguments there are, or their types.
2188 (For example, the function might return a result of type $\alpha$.)
2190 \item Below each pending-argument section is another return address,
2191 and so on. Actually, there might be an update frame instead, but we
2192 can consider update frames as a special case of a return address with
2193 a well-defined activation record.
2195 \ToDo{Doesn't it {\em have} to be an update frame? After all, the arg
2196 satisfaction check is @Su - Sp >= ...@.}
2200 The game plan is this. The garbage collector
2201 walks the stack from the top, traversing pending-argument sections and
2202 activation records alternately. Next we discuss how it finds
2203 the pointers in each of these two stack regions.
2206 \subsubsection{Activation records}\label{sect:activation-records}
2208 An {\em activation record} is a contiguous chunk of stack,
2209 with a return address as its first word, followed by as many
2210 data words as the return address ``knows about''. The return
2211 address is actually a fully-fledged info pointer. It points
2212 to an info table, replete with:
2215 \item entry code (i.e. the code to return to).
2216 \item @INFO_TYPE@ is either @RET_SMALL/RET_VEC_SMALL@ or @RET_BIG/RET_VEC_BIG@, depending
2217 on whether the activation record has more than 32 data words (\note{64 for 8-byte-word architectures}) and on whether
2218 to use a direct or a vectored return.
2219 \item @INFO_SM@ for @RET_SMALL@ is a bitmap telling the layout
2220 of the activation record, one bit per word. The least-significant bit
2221 describes the first data word of the record (adjacent to the fixed
2222 header) and so on. A ``@1@'' indicates a non-pointer, a ``@0@''
2224 a pointer. We don't need to indicate exactly how many words there
2226 because when we get to all zeros we can treat the rest of the
2227 activation record as part of the next pending-argument region.
2229 For @RET_BIG@ the @INFO_SM@ field points to a block of bitmap
2230 words, starting with a word that tells how many words are in
2233 \item @INFO_SRT@ is the Static Reference Table for the return
2234 address (Section~\ref{sect:srt}).
2237 The activation record is a fully fledged closure too.
2238 As well as an info pointer, it has all the other attributes of
2239 a fixed header (Section~\ref{sect:fixed-header}) including a saved cost
2240 centre which is reloaded when the return address is entered.
2242 In other words, all the attributes of closures are needed for
2243 activation records, so it's very convenient to make them look alike.
2246 \subsubsection{Pending arguments}
2248 So that the garbage collector can correctly identify pointers
2249 in pending-argument sections we explicitly tag all non-pointers.
2250 Every non-pointer in a pending-argument section is preceded
2251 (at the next lower memory word) by a one-word byte count that
2252 says how many bytes to skip over (excluding the tag word).
2254 The garbage collector traverses a pending argument section from
2255 the top (i.e. lowest memory address). It looks at each word in turn:
2258 \item If it is less than or equal to a small constant @MAX_STACK_TAG@
2260 it treats it as a tag heralding zero or more words of non-pointers,
2261 so it just skips over them.
2263 \item If it points to the code segment, it must be a return
2264 address, so we have come to the end of the pending-argument section.
2266 \item Otherwise it must be a bona fide heap pointer.
2270 \subsection{The Stable Pointer Table}\label{sect:STABLEPTR_TABLE}
2272 A stable pointer is a name for a Haskell object which can be passed to
2273 the external world. It is ``stable'' in the sense that the name does
2274 not change when the Haskell garbage collector runs---in contrast to
2275 the address of the object which may well change.
2277 A stable pointer is represented by an index into the
2278 @StablePointerTable@. The Haskell garbage collector treats the
2279 @StablePointerTable@ as a source of roots for GC.
2281 In order to provide efficient access to stable pointers and to be able
2282 to cope with any number of stable pointers (eg $0 \ldots 100000$), the
2283 table of stable pointers is an array stored on the heap and can grow
2284 when it overflows. (Since we cannot compact the table by moving
2285 stable pointers about, it seems unlikely that a half-empty table can
2286 be reduced in size---this could be fixed if necessary by using a
2287 hash table of some sort.)
2289 In general a stable pointer table closure looks like this:
2292 \begin{tabular}{|l|l|l|l|l|l|l|l|l|l|l|}
2294 {\em Fixed header} & {\em No of pointers} & {\em Free} & $SP_0$ & \ldots & $SP_{n-1}$
2302 \item[@NPtrs@:] number of (stable) pointers.
2304 \item[@Free@:] the byte offset (from the first byte of the object) of the first free stable pointer.
2306 \item[$SP_i$:] A stable pointer slot. If this entry is in use, it is
2307 an ``unstable'' pointer to a closure. If this entry is not in use, it
2308 is a byte offset of the next free stable pointer slot.
2312 When a stable pointer table is evacuated
2314 \item the free list entries are all set to @NULL@ so that the evacuation
2315 code knows they're not pointers;
2317 \item The stable pointer slots are scanned linearly: non-@NULL@ slots
2318 are evacuated and @NULL@-values are chained together to form a new free list.
2321 There's no need to link the stable pointer table onto the mutable
2322 list because we always treat it as a root.
2326 \section{The Storage Manager}
2328 The generational collector remembers the depth of the last generation
2329 collected and the value of the heap pointer at the end of the last GC.
2330 If the mutator has not moved the heap pointer, that means that the
2331 amount of space recovered is insufficient to satisfy even one request
2332 and it is time to collect an older generation or report a heap overflow.
2334 A deeper collection is also triggered when a minor collection fails to
2335 recover at least @...@ bytes of space.
2337 When can a GC happen?
2340 - During updates (ie during returns)
2341 - When a heap check fails
2342 - When a stack check fails (concurrent system only)
2343 - When a context switch happens (concurrent system only)
2345 When do heap checks occur?
2346 - Immediately after entering a thunk
2347 - Immediately after entering a case alternative
2349 When do stack checks occur?
2350 - We calculate the worst-case stack usage of an entire
2351 thunk so there's no need to put a check inside each alternative.
2352 - Immediately after entering a thunk
2353 We can't make a similar worst-case calculation for heap usage
2354 because the heap isn't used in a stacklike manner so any
2355 evaluation inside a case might steal some of the heap we've
2359 - Threads can be blocked
2360 - Threads can be put to sleep
2361 - Heap may move while we sleep
2362 - Black holing may happen while we sleep (ie during GC)
2365 \subsection{The SM state}
2367 Contains @Hp@, @HpLim@, @StablePtrTable@ plus version-specific info.
2371 \item Static Object list
2372 \item Foreign Object list
2373 \item Stable Pointer Table
2377 In addition, the generational collector requires:
2381 \item Old Generation Indirection list
2382 \item Mutables list --- list of mutable objects in the old generation.
2383 \item @OldLim@ --- the boundary between the generations
2384 \item Old Foreign Object list --- foreign objects in the old generation
2388 It is passed a table of {\em roots\/} containing
2392 \item All runnable TSOs
2397 In the parallel system, there must be some extra magic associated with
2400 \subsection{The SM interface}
2402 @initSM@ finalizes any runtime parameters of the storage manager.
2404 @exitSM@ does any cleaning up required by the storage manager before
2405 the program is executed. Its main purpose is to print any summary
2408 @initHeap@ allocates the heap. It initialises the @hp@ and @hplim@
2409 fields of @sm@ to represent an empty heap for the compiled-in garbage
2410 collector. It also initialises @CAFlist@ to be the empty list. If we
2411 are using Appel's collector it also initialises the @OldLim@ field.
2412 It also initialises the stable pointer table and the @ForeignObjList@
2413 (and @OldForeignObjList@) fields.
2415 @collectHeap@ invokes the garbage collector. @collectHeap@ requires
2416 all the fields of @sm@ to be initialised appropriately (from the
2417 STG-machine registers). The following are identified as heap roots:
2419 \item The updated CAFs recorded in @CAFlist@.
2420 \item Any pointers found on the stack.
2421 \item All runnable and sleeping TSOs.
2422 \item The stable pointer table.
2425 There are two possible results from a garbage collection:
2428 The garbage collector is unable to free up any more space.
2431 The garbage collector managed to free up more space.
2434 \item @hp@ and @hplim@ will indicate the new space available for
2437 \item The elements of @CAFlist@ and the stable pointers will be
2438 updated to point to the new locations of the closures they reference.
2440 \item Any members of @ForeignObjList@ which became garbage should have
2441 been reported (by calling their finalising routines; and the
2442 @(Old)ForeignObjList@ updated to contain only those Foreign objects
2443 which are still live.
2450 %************************************************************************
2452 \subsection{``What really happens in a garbage collection?''}
2454 %************************************************************************
2456 This is a brief tutorial on ``what really happens'' going to/from the
2457 storage manager in a garbage collection.
2460 %------------------------------------------------------------------------
2461 \item[The heap check:]
2465 If you gaze into the C output of GHC, you see many macros calls like:
2467 HEAP_CHK_2PtrsLive((_FHS+2));
2470 This expands into the C (roughly speaking...):
2472 Hp = Hp + (_FHS+2); /* optimistically move heap pointer forward */
2474 GC_WHILE_OR_IF (HEAP_OVERFLOW_OP(Hp, HpLim) OR_INTERVAL_EXPIRED) {
2475 STGCALL2_GC(PerformGC, <liveness-bits>, (_FHS+2));
2479 In the parallel world, where we will need to re-try the heap check,
2480 @GC_WHILE_OR_IF@ will be a ``while''; in the sequential world, it will
2483 The ``heap lookahead'' checks, which are similar and used for
2484 multi-precision @Integer@ ops, have some further complications. See
2485 the commentary there (@StgMacros.lh@).
2487 %------------------------------------------------------------------------
2488 \item[Into @callWrapper_GC@...:]
2490 When we failed the heap check (above), we were inside the
2491 GCC-registerised ``threaded world.'' @callWrapper_GC@ is all about
2492 getting in and out of the threaded world. On SPARCs, with register
2493 windows, the name of the game is not shifting windows until we have
2494 what we want out of the old one. In tricky cases like this, it's best
2495 written in assembly language.
2497 Performing a GC (potentially) means giving up the thread of control.
2498 So we must fill in the thread-state-object (TSO) [and its associated
2499 stk object] with enough information for later resumption:
2502 Save the return address in the TSO's PC field.
2504 Save the machine registers used in the STG threaded world in their
2505 corresponding TSO fields. We also save the pointer-liveness
2506 information in the TSO.
2508 The registers that are not thread-specific, notably @Hp@ and
2509 @HpLim@, are saved in the @StorageMgrInfo@ structure.
2511 Call the routine it was asked to call; in this example, call
2512 @PerformGC@ with arguments @<liveness>@ and @_FHS+2@ (some constant)...
2516 %------------------------------------------------------------------------
2517 \item[Into the heap overflow wrapper, @PerformGC@ [parallel]:]
2519 Most information has already been saved in the TSO.
2523 The first argument (@<liveness>@, in our example) say what registers
2524 are live, i.e., are ``roots'' the storage manager needs to know.
2526 StorageMgrInfo.rootno = 2;
2527 StorageMgrInfo.roots[0] = (P_) Ret1_SAVE;
2528 StorageMgrInfo.roots[1] = (P_) Ret2_SAVE;
2532 We move the heap-pointer back [we had optimistically
2533 advanced it, in the initial heap check]
2536 We load up the @smInfo@ data from the STG registers' @*_SAVE@ locations.
2539 We mark on the scheduler's big ``blackboard'' that a GC is
2543 We reschedule, i.e., this thread gives up control. (The scheduler
2544 will presumably initiate a garbage-collection, but it may have to do
2545 any number of other things---flushing, for example---before ``normal
2546 execution'' resumes; and it most certainly may not be this thread that
2547 resumes at that point!)
2550 IT IS AT THIS POINT THAT THE WORLD IS COMPLETELY TIDY.
2552 %------------------------------------------------------------------------
2553 \item[Out of @callWrapper_GC@ [parallel]:]
2555 When this thread is finally resumed after GC (and who knows what
2556 else), it will restart by the normal enter-TSO/enter-stack-object
2557 sequence, which has the effect of re-loading the registers, etc.,
2558 (i.e., restoring the state).
2560 Because the address we saved in the TSO's PC field was that at the end
2561 of the heap check, and because the check is a while-loop in the
2562 parallel system, we will now loop back around, and make sure there is
2563 enough space before continuing.
2568 \subsection{Static Reference Tables (SRTs)}
2571 \label{sect:static-objects}
2573 In the above, we assumed that objects always contained pointers to all
2574 their free variables. In fact, this isn't quite true: GHC omits
2575 pointers to top-level objects and allocates their closures in static
2576 memory. This optimisation reduces the number of free variables in
2577 heap objects - reducing memory usage and the effort needed to put them
2578 into heap objects. However, this optimisation comes at a cost: we
2579 need to complicate the garbage collector with machinery for tracing
2580 these static references.
2582 Early versions of GHC used a very simple algorithm: it treated all
2583 static objects as roots. This is safe in the sense that no object is
2584 ever deallocated if there's a chance that it might be required later
2585 but can lead to some terrible space leaks. For example, this program
2586 ought to be able to run in constant space but, because @xs@ is never
2587 deallocated, it runs in linear space.
2594 The correct behaviour is for the garbage collector to keep a static
2595 object alive iff it might be required later in execution. That is, if
2596 it is reachable from any live heap objects {\em or\/} from any return
2597 addresses found on the stack or from the current program counter.
2598 Since it is obviously infeasible for the garbage collector to scan
2599 machine code looking for static references, the code generator must
2600 generate a table of all static references in any piece of code (and we
2601 must place a pointer to this table next to any piece of code we
2604 Here's what the SRT has to contain:
2610 Here's how we represent it:
2614 must be able to handle 0 references well
2621 o Generational GC trickery
2624 \subsection{Space leaks and black holes}
2625 \label{sect:black-hole}
2629 \ToDo{Insert text stolen from update paper}
2633 A program exhibits a {\em space leak} if it retains storage that is
2634 sure not to be used again. Space leaks are becoming increasingly
2635 common in imperative programs that @malloc@ storage and fail
2636 subsequently to @free@ it. They are, however, also common in
2637 garbage-collected systems, especially where lazy evaluation is
2638 used.[.wadler leak, runciman heap profiling jfp.]
2640 Quite a bit of experience has now accumulated suggesting that
2641 implementors must be very conscientious about avoiding gratuitous
2642 space leaks --- that is, ones which are an accidental artefact of some
2643 implementation technique.[.appel book.] The update mechanism is
2644 a case in point, as <.jones jfp leak.> points out. Consider a thunk for
2647 let xs = [1..1000] in last xs
2649 where @last@ is a function that returns the last element of its
2650 argument list. When the thunk is entered it will call @last@, which
2651 will consume @xs@ until it finds the last element. Since the list
2652 @[1..1000]@ is produced lazily one might reasonably expect the
2653 expression to evaluate in constant space. But {\em until the moment
2654 of update, the thunk itself still retains a pointer to the beginning
2655 of the list @xs@}. So, until the update takes place the whole list
2658 Of course, this is completely gratuitous. The pointer to @xs@ in the
2659 thunk will never be used again. In <.peyton stock hardware.> the solution to
2660 this problem that we advocated was to overwrite a thunk's info with a
2661 fixed ``black hole'' info pointer, {\em at the moment of entry}. The
2662 storage management information attached to a black-hole info pointer
2663 tells the garbage collector that the closure contains no pointers,
2664 thereby plugging the space leak.
2666 \subsubsection{Lazy black-holing}
2668 Black-holing is a well-known idea. The trouble is that it is
2669 gallingly expensive. To avoid the occasional space leak, for every
2670 single thunk entry we have to load a full-word literal constant into a
2671 register (often two instructions) and then store that register into a
2674 Fortunately, this cost can easily be avoided. The
2675 idea is simple: {\em instead of black-holing every thunk on entry,
2676 wait until the garbage collector is called, and then black-hole all
2677 (and only) the thunks whose evaluation is in progress at that moment}.
2678 There is no benefit in black-holing a thunk that is updated before
2679 garbage collection strikes! In effect, the idea is to perform the
2680 black-holing operation lazily, only when it is needed. This
2681 dramatically cuts down the number of black-holing operations, as our
2682 results show {\em forward ref}.
2684 How can we find all the thunks whose evaluation is in progress? They
2685 are precisely the ones for which update frames are on the stack. So
2686 all we need do is find all the update frames (via the @Su@ chain) and
2687 black-hole their thunks right at the start of garbage collection.
2688 Notice that it is not enough to refrain from treating update frames as
2689 roots: firstly because the thunks to which they point may need to be
2690 moved in a copying collector, but more importantly because the thunk
2691 might be accessible via some other route.
2693 \subsubsection{Detecting loops}
2695 Black-holing has a second minor advantage: evaluation of a thunk whose
2696 value depends on itself will cause a black hole closure to be entered,
2697 which can cause a suitable error message to be displayed. For example,
2698 consider the definition
2702 The code to evaluate @x@'s right hand side will evaluate @x@. In the
2703 absence of black-holing, the result will be a stack overflow, as the
2704 evaluator repeatedly pushes a return address and enters @x@. If
2705 thunks are black-holed on entry, then this infinite loop can be caught
2708 With our new method of lazy black-holing, a self-referential program
2709 might cause either stack overflow or a black-hole error message,
2710 depending on exactly when garbage collection strikes. It is quite
2711 easy to conceal these differences, however. If stack overflow occurs,
2712 all we need do is examine the update frames on the stack to see if
2713 more than one refers to the same thunk. If so, there is a loop that
2714 would have been detected by eager black-holing.
2716 \subsubsection{Lazy locking}
2719 In a parallel implementation, it is necessary somehow to ``lock'' a
2720 thunk that is under evaluation, so that other parallel evaluators
2721 cannot simultaneously evaluate it and thereby duplicate work.
2722 Instead, an evaluator that enters a locked thunk should be blocked,
2723 and made runnable again when the thunk is updated.
2725 This locking is readily arranged in the same way as black-holing, by
2726 overwriting the thunk's info pointer with a special ``locked'' info
2727 pointer, at the moment of entry. If another evaluator enters the
2728 thunk before it has been updated, it will land in the entry code for
2729 the ``locked'' info pointer, which blocks the evaluator and queues it
2730 on the locked thunk.
2732 The details are given by <.portable parallel trinder.>. However, the close similarity
2733 between locking and black holing suggests the following question: can
2734 locking be done lazily too? The answer is that it can, except that
2735 locking can be postponed only until the next {\em context switch},
2736 rather than the next {\em garbage collection}. We are assuming here
2737 that the parallel implementation does not use shared memory to allow
2738 two processors to access the same closure. If such access is
2739 permitted then every thunk entry requires a hardware lock, and becomes
2742 Is lazy locking worth while, given that it requires extra work every
2743 context switch? We believe it is, because contexts switches are
2744 relatively infrequent, and thousands of thunk-entries typically take
2747 {\em Measurements elsewhere. Omit this section? If so, fix cross refs to here.}
2752 \subsection{Squeezing identical updates}
2756 \ToDo{Insert text stolen from update paper}
2760 Consider the following Haskell definition of the standard
2761 function @partition@ that divides a list into two, those elements
2762 that satisfy a predicate @p@ and those that do not:
2764 partition :: (a->Bool) -> [a] -> ([a],[a])
2765 partition p [] = ([],[])
2766 partition p (x:xs) = if p x then (x:ys, zs)
2769 (ys,zs) = partition p xs
2771 By the time this definition has been desugared, it looks like this:
2781 if p x then (x:ys,zs)
2784 Lazy evaluation demands that the recursive call is bound to an
2785 intermediate variable, @t@, from which @ys@ and @zs@ are lazily
2786 selected. (The functions @fst@ and @snd@ select the first and second
2787 elements of a pair, respectively.)
2789 Now, suppose that @partition@ is applied to a list @[x1,x2]@,
2791 elements satisfy @p@. We can get a good idea of what will happen
2792 at runtime by unrolling the recursion a few times in our heads.
2793 Unrolling once, and remembering that @(p x1)@ is @True@, we get this:
2797 let t1 = partition [x2]
2802 Unrolling the rest of the way gives this:
2814 Now consider what happens if @zs1@ is evaluated. It is bound to a
2815 thunk, which will push an update frame before evaluating the
2816 expression @snd t1@. This expression in turn forces evaluation of
2817 @zs2@, which pushes an update frame before evaluating @snd t2@.
2818 Indeed the stack of update frames will grow as deep as the list is
2819 long when @zs1@ is evaluated. This is rather galling, since all the
2820 thunks @zs1@, @zs2@, and so on, have the same value.
2822 \ToDo{Describe the state-transformer case in which we get a space leak from
2823 pending update frames.}
2825 The solution is simple. The garbage collector, which is going to traverse the
2826 update stack in any case, can easily identify two update frames that are directly
2827 on top of each other. The second of these will update its target with the same
2828 value as the first. Therefore, the garbage collector can perform the update
2829 right away, by overwriting one update target with an indirection to the second,
2830 and eliminate the corresponding update frame. In this way ever-growing stacks of
2831 update frames are reduced to a single representative at garbage collection time.
2832 If this is done at the start of garbage collection then, if it turns out that
2833 some of these update targets are garbage they will be collected right away.
2837 \subsection{Space leaks and selectors}
2841 \ToDo{Insert text stolen from update paper}
2845 In 1987, Wadler identified an important source of space leaks in
2846 lazy functional programs. Consider the Haskell function definition:
2848 f p = (g1 a, g2 b) where (a,b) = p
2850 The pattern-matching in the @where@ clause is known as
2851 {\em lazy pattern-matching}, because it is performed only if @a@
2852 or @b@ is actually evaluated. The desugarer translates lazy pattern matching
2853 to the use of selectors, @fst@ and @snd@ in this case:
2860 Now suppose that the second component of the pair @(f p)@, namely @a@,
2861 is evaluated and discarded, but the first is not although it remains
2862 reachable. The garbage collector will find that the thunk for @b@ refers
2863 to @p@ and hence to @a@. Thus, although @a@ cannot ever be used again, its
2864 space is retained. It turns out that this space leak can have a very bad effect
2865 indeed on a program's space behaviour (Section~\ref{sect:selector-results}).
2867 Wadler's paper also proposed a solution: if the garbage collector
2868 encounters a thunk of the form @snd p@, where @p@ is evaluated, then
2869 the garbage collector should perform the selection and overwrite the
2870 thunk with a pointer to the second component of the pair. In effect, the
2871 garbage collector thereby performs a bounded amount of as-yet-undemanded evaluation
2872 in the hope of improving space behaviour.
2873 We implement this idea directly, by making the garbage collector
2874 eagerly execute all selector thunks\footnote{A word of caution: it is rather easy
2875 to make a mistake in the implementation, especially if the garbage collector
2876 uses pointer reversal to traverse the reachable graph.},
2878 reported in Section~\ref{sect:THUNK_SEL}.
2880 One could easily imagine generalisations of this idea, with the garbage
2881 collector performing bounded amounts of space-saving work. One example is
2885 f x (y:ys) = f (x+1) ys
2887 Most lazy evaluators will build up a chain of thunks for the accumulating
2888 parameter, @x@, each of which increments @x@. It is not safe to evaluate
2889 any of these thunks eagerly, since @f@ is not strict in @x@, and we know nothing
2890 about the value of @x@ passed in the initial call to @f@.
2891 On the other hand, if the garbage collector found a thunk @(x+1)@ where
2892 @x@ happened to be evaluated, then it could ``execute'' it eagerly.
2893 If done carefully, the entire chain could be eliminated in a single
2894 garbage collection. We have not (yet) implemented this idea.
2895 A very similar idea, dubbed ``stingy evaluation'', is described
2898 <.sparud lazy pattern matching.> describes another solution to the
2899 lazy-pattern-matching
2900 problem. His solution involves adding code to the two thunks for
2901 @a@ and @b@ so that if either is evaluated it arranges to update the
2902 other as well as itself. The garbage-collector solution is a little
2903 more general, since it applies whether or not the selectors were
2904 generated by lazy pattern matching, and in our setting it was easier
2905 to implement than Sparud's.
2910 \subsection{Internal workings of the Compacting Collector}
2912 \subsection{Internal workings of the Copying Collector}
2914 \subsection{Internal workings of the Generational Collector}
2917 \section{Dynamic Linking}
2921 Registering costs centres looks awkward - can we tidy it up?
2923 \section{Parallelism}
2925 Something about global GC, inter-process messages and fetchmes.
2929 \section{Ticky Ticky profiling}
2931 Measure what proportion of ...:
2934 ... Enters are to data values, function values, thunks.
2936 ... allocations are for data values, functions values, thunks.
2938 ... updates are for data values, function values.
2942 ... return-in-heap (dynamic)
2944 ... vectored return (dynamic)
2946 ... updates are wasted (never re-entered).
2948 ... constructor returns get away without hitting an update.
2951 %************************************************************************
2953 \subsubsection[ticky-stk-heap-use]{Stack and heap usage}
2955 %************************************************************************
2957 Things we are interested in here:
2960 How many times we do a heap check and move @Hp@; comparing this with
2961 the allocations gives an indication of how many things we get per trip
2964 If we do a ``heap lookahead,'' we haven't really allocated any
2965 heap, so we need to undo the effects of an @ALLOC_HEAP@:
2968 The stack high-water mark.
2971 Re-use of stack slots, and stubbing of stack slots:
2975 %************************************************************************
2977 \subsubsection[ticky-allocs]{Allocations}
2979 %************************************************************************
2981 We count things every time we allocate something in the dynamic heap.
2982 For each, we count the number of words of (1)~``admin'' (header),
2983 (2)~good stuff (useful pointers and data), and (3)~``slop'' (extra
2984 space, in hopes it will allow an in-place update).
2986 The first five macros are inserted when the compiler generates code
2987 to allocate something; the categories correspond to the @ClosureClass@
2988 datatype (manifest functions, thunks, constructors, big tuples, and
2989 partial applications).
2991 We may also allocate space when we do an update, and there isn't
2992 enough space. These macros suffice (for: updating with a partial
2993 application and a constructor):
2995 In the threaded world, we allocate space for the spark pool, stack objects,
2996 and thread state objects.
2998 The histogrammy bit is fairly straightforward; the @-2@ is: one for
2999 0-origin C arrays; the other one because we do {\em no} one-word
3000 allocations, so we would never inc that histogram slot; so we shift
3001 everything over by one.
3003 Some hard-to-account-for words are allocated by/for primitives,
3004 includes Integer support. @ALLOC_PRIM2@ tells us about these. We
3005 count everything as ``goods'', which is not strictly correct.
3006 (@ALLOC_PRIM@ is the same sort of stuff, but we know the
3007 admin/goods/slop breakdown.)
3009 %************************************************************************
3011 \subsubsection[ticky-enters]{Enters}
3013 %************************************************************************
3015 We do more magical things with @ENT_FUN_DIRECT@. Besides simply knowing
3016 how many ``fast-entry-point'' enters there were, we'd like {\em simple}
3017 information about where those enters were, and the properties thereof.
3019 struct ent_counter {
3020 unsigned registeredp:16, /* 0 == no, 1 == yes */
3021 arity:16, /* arity (static info) */
3022 Astk_args:16, /* # of args off A stack */
3023 Bstk_args:16; /* # of args off B stack */
3024 /* (rest of args are in registers) */
3025 StgChar *f_str; /* name of the thing */
3026 StgChar *f_arg_kinds; /* info about the args types */
3027 StgChar *wrap_str; /* name of its wrapper (if any) */
3028 StgChar *wrap_arg_kinds;/* info about the orig wrapper's arg types */
3029 I_ ctr; /* the actual counter */
3030 struct ent_counter *link; /* link to chain them all together */
3034 %************************************************************************
3036 \subsubsection[ticky-returns]{Returns}
3038 %************************************************************************
3040 Whenever a ``return'' occurs, it is returning the constituent parts of
3041 a data constructor. The parts can be returned either in registers, or
3042 by allocating some heap to put it in (the @ALLOC_*@ macros account for
3043 the allocation). The constructor can either be an existing one
3044 (@*OLD*@) or we could have {\em just} figured out this stuff
3047 Here's some special magic that Simon wants [edited to match names
3051 From: Simon L Peyton Jones <simonpj>
3052 To: partain, simonpj
3053 Subject: counting updates
3054 Date: Wed, 25 Mar 92 08:39:48 +0000
3056 I'd like to count how many times we update in place when actually Node
3057 points to the thing. Here's how:
3059 @RET_OLD_IN_REGS@ sets the variable @ReturnInRegsNodeValid@ to @True@;
3060 @RET_NEW_IN_REGS@ sets it to @False@.
3062 @RET_SEMI_???@ sets it to??? ToDo [WDP]
3064 @UPD_CON_IN_PLACE@ tests the variable, and increments @UPD_IN_PLACE_COPY_ctr@
3067 Then we need to report it along with the update-in-place info.
3071 Of all the returns (sum of four categories above), how many were
3072 vectored? (The rest were obviously unvectored).
3074 %************************************************************************
3076 \subsubsection[ticky-update-frames]{Update frames}
3078 %************************************************************************
3080 These macros count up the following update information.
3082 \begin{tabular}{|l|l|} \hline
3083 Macro & Counts \\ \hline
3085 @UPDF_STD_PUSHED@ & Update frame pushed \\
3086 @UPDF_CON_PUSHED@ & Constructor update frame pushed \\
3087 @UPDF_HOLE_PUSHED@ & An update frame to update a black hole \\
3088 @UPDF_OMITTED@ & A thunk decided not to push an update frame \\
3089 & (all subsets of @ENT_THK@) \\
3090 @UPDF_RCC_PUSHED@ & Cost Centre restore frame pushed \\
3091 @UPDF_RCC_OMITTED@ & Cost Centres not required -- not pushed \\\hline
3094 %************************************************************************
3096 \subsubsection[ticky-updates]{Updates}
3098 %************************************************************************
3100 These macros record information when we do an update. We always
3101 update either with a data constructor (CON) or a partial application
3104 \begin{tabular}{|l|l|}\hline
3105 Macro & Where \\ \hline
3107 @UPD_EXISTING@ & Updating with an indirection to something \\
3108 & already in the heap \\
3109 @UPD_SQUEEZED@ & Same as @UPD_EXISTING@ but because \\
3110 & of stack-squeezing \\
3111 @UPD_CON_W_NODE@ & Updating with a CON: by indirecting to Node \\
3112 @UPD_CON_IN_PLACE@ & Ditto, but in place \\
3113 @UPD_CON_IN_NEW@ & Ditto, but allocating the object \\
3114 @UPD_PAP_IN_PLACE@ & Same, but updating w/ a PAP \\
3115 @UPD_PAP_IN_NEW@ & \\\hline
3118 %************************************************************************
3120 \subsubsection[ticky-selectors]{Doing selectors at GC time}
3122 %************************************************************************
3124 @GC_SEL_ABANDONED@: we could've done the selection, but we gave up
3125 (e.g., to avoid overflowing the C stack); @GC_SEL_MINOR@: did a
3126 selection in a minor GC; @GC_SEL_MAJOR@: ditto, but major GC.
3132 We're nuking the following:
3139 Return in registers.
3140 This lets us remove update code pointers from info tables,
3141 removes the need for phantom info tables, simplifies
3146 Careful analysis suggests that it doesn't buy us very much
3147 and it is hard to work with.
3149 Eliminating threaded GCs eliminates the desire to share SMReps
3150 so they are (once more) part of the Info table.
3154 Doesn't buy us anything on a register-poor architecture and
3155 isn't so important if we have semi-tagging.
3158 - Probably bad on register poor architecture
3159 - Can avoid need to write return address to stack on reg rich arch.
3160 - when a function does a small amount of work, doesn't
3161 enter any other thunks and then returns.
3162 eg entering a known constructor (but semitagging will catch this)
3163 - Adds complications
3169 This lets us drop CONST closures and CHARLIKE closures (assuming we
3170 don't support Unicode). The only point of these closures was to
3171 avoid updating with an indirection.
3173 We also drop @MIN_UPD_SIZE@ --- all we need is space to insert an
3174 indirection or a black hole.
3177 STATIC SMReps are now called CONST
3182 \item The profiling ``kind'' field is now encoded in the @INFO_TYPE@ field.
3183 This identifies the general sort of the closure for profiling purposes.
3185 \item Various papers describe deleting update frames for unreachable objects.
3186 This has never been implemented and we don't plan to anytime soon.
3190 \section{Old tricks}
3194 These are statically defined closures which have been updated with a
3195 heap-allocated result. Initially these are exactly the same as a
3196 @STATIC@ closure but with special entry code. On entering the closure
3197 the entry code must:
3200 \item Allocate a black hole in the heap which will be updated with
3202 \item Overwrite the static closure with a special @CAF@ indirection.
3204 \item Link the static indirection onto the list of updated @CAF@s.
3207 The indirection and the link field require the initial @STATIC@
3208 closure to be of at least size @MIN_UPD_SIZE@ (excluding the fixed
3211 @CAF@s are treated as special garbage collection roots. These roots
3212 are explicitly collected by the garbage collector, since they may
3213 appear in code even if they are not linked with the main heap. They
3214 consequently represent potentially enormous space-leaks. A @CAF@
3215 closure retains a fixed location in statically allocated data space.
3216 When updated, the contents of the @CAF@ indirection are changed to
3217 reflect the new closure. @CAF@ indirections require special garbage
3220 \section{Old stuff about SRTs}
3222 Garbage collection of @CAF@s is tricky. We have to cope with explicit
3223 collection from the @CAFlist@ as well as potential references from the
3224 stack and heap which will cause the @CAF@ evacuation code to be
3225 called. They are treated like indirections which are shorted out.
3226 However they must also be updated to point to the new location of the
3227 new closure as the @CAF@ may still be used by references which
3230 {\bf Copying Collection}
3232 A first scheme might use evacuation code which evacuates the reference
3233 and updates the indirection. This is no good as subsequent evacuations
3234 will result in an already evacuated closure being evacuated. This will
3235 leave a forward reference in to-space!
3237 An alternative scheme evacuates the @CAFlist@ first. The closures
3238 referenced are evacuated and the @CAF@ indirection updated to point to
3239 the evacuated closure. The @CAF@ evacuation code simply returns the
3240 updated indirection pointer --- the pointer to the evacuated closure.
3241 Unfortunately the closure the @CAF@ references may be a static
3242 closure, in fact, it may be another @CAF@. This will cause the second
3243 @CAF@'s evacuation code to be called before the @CAF@ has been
3244 evacuated, returning an unevacuated pointer.
3246 Another scheme leaves updating the @CAF@ indirections to the end of
3247 the garbage collection. All the references are evacuated and
3248 scavenged as usual (including the @CAFlist@). Once collection is
3249 complete the @CAFlist@ is traversed updating the @CAF@ references with
3250 the result of evacuating the referenced closure again. This will
3251 immediately return as it must be a forward reference, a static
3252 closure, or a @CAF@ which will indirect by evacuating its reference.
3254 The crux of the problem is that the @CAF@ evacuation code needs to
3255 know if its reference has already been evacuated and updated. If not,
3256 then the reference can be evacuated, updated and returned safely
3257 (possibly evacuating another @CAF@). If it has, then the updated
3258 reference can be returned. This can be done using two @CAF@
3259 info-tables. At the start of a collection the @CAFlist@ is traversed
3260 and set to an internal {\em evacuate and update} info-table. During
3261 collection, evacution of such a @CAF@ also results in the info-table
3262 being reset back to the standard @CAF@ info-table. Thus subsequent
3263 evacuations will simply return the updated reference. On completion of
3264 the collection all @CAF@s will have {\em return reference} info-tables
3267 This is the scheme we adopt. A @CAF@ indirection has evacuation code
3268 which returns the evacuated and updated reference. During garbage
3269 collection, all the @CAF@s are overwritten with an internal @CAF@ info
3270 table which has evacuation code which performs this evacuate and
3271 update and restores the original @CAF@ code. At some point during the
3272 collection we must ensure that all the @CAF@s are indeed evacuated.
3274 The only potential problem with this scheme is a cyclic list of @CAF@s
3275 all directly referencing (possibly via indirections) another @CAF@!
3276 Evacuation of the first @CAF@ will fail in an infinite loop of @CAF@
3277 evacuations. This is solved by ensuring that the @CAF@ info-table is
3278 updated to a {\em return reference} info-table before performing the
3279 evacuate and update. If this {\em return reference} evacuation code is
3280 called before the actual evacuation is complete it must be because
3281 such a cycle of references exists. Returning the still unevacuated
3282 reference is OK --- all the @CAF@s will now reference the same
3283 @CAF@ which will reference itself! Construction of such a structure
3284 indicates the program must be in an infinite loop.
3286 {\bf Compacting Collector}
3288 When shorting out a @CAF@, its reference must be marked. A first
3289 attempt might explicitly mark the @CAF@s, updating the reference with
3290 the marked reference (possibly short circuting indirections). The
3291 actual @CAF@ marking code can indicate that they have already been
3292 marked (though this might not have actually been done yet) and return
3293 the indirection pointer so it is shorted out. Unfortunately the @CAF@
3294 reference might point to an indirection which will be subsequently
3295 shorted out. Rather than returning the @CAF@ reference we treat the
3296 @CAF@ as an indirection, calling the mark code of the reference, which
3297 will return the appropriately shorted reference.
3299 Problem: Cyclic list of @CAF@s all directly referencing (possibly via
3300 indirections) another @CAF@!
3302 Before compacting, the locations of the @CAF@ references are
3303 explicitly linked to the closures they reference (if they reference
3304 heap allocated closures) so that the compacting process will update
3305 them to the closure's new location. Unfortunately these locations'
3306 @CAF@ indirections are static. This causes premature termination
3307 since the test to find the info pointer at the end of the location
3308 list will match more than one value. This can be solved by using an
3309 auxiliary dynamic array (on the top of the A stack). One location for
3310 each @CAF@ indirection is linked to the closure that the @CAF@
3311 references. Once collection is complete this array is traversed and
3312 the corresponding @CAF@ is then updated with the updated pointer from
3313 the auxiliary array.
3316 It is possible to use an alternative marking scheme, using a similar
3317 idea to the copying solution. This scheme avoids the need to update
3318 the @CAF@ references explicitly. We introduce an auxillary {\em mark
3319 and update} @CAF@ info-table which is used to update all @CAF@s at the
3320 start of a collection. The new code marks the @CAF@ reference,
3321 updating it with the returned reference. The returned reference is
3322 itself returned so the @CAF@ is shorted out. The code also modifies the
3323 @CAF@ info-table to be a {\em return reference}. Subsequent attempts to
3324 mark the @CAF@ simply return the updated reference.
3326 A cyclic @CAF@ reference will result in an attempt to mark the @CAF@
3327 before the marking has been completed and the reference updated. We
3328 cannot start marking the @CAF@ as it is already being marked. Nor can
3329 we return the reference as it has not yet been updated. Neither can we
3330 treat the CAF as an indirection since the @CAF@ reference has been
3331 obscured by the pointer reversal stack. All we can do is return the
3332 @CAF@ itself. This will result in some @CAF@ references not being
3335 This scheme has not been adopted but has been implemented. The code is
3336 commented out with @#if 0@.
3338 \subsection{The virtual register set}
3340 We refer to any (atomic) part of the virtual machine state as a ``register.''
3341 These ``registers'' may be shared between all threads in the system or may be
3342 specific to each thread.
3348 Thread preemption flag
3353 TSO - pointer to the TSO for when we have to pack thread away
3356 Su - used to calculate number of arguments on stack
3357 - this is a more convenient representation
3358 Call/return registers (aka General purpose registers)
3359 Cost centre (and other debug/profile info)
3360 Statistic gathering (not in production system)
3362 Heap overflow - possible global?
3363 Stack overflow - possibly global?
3364 Pattern match failure
3365 maybe a failWith handler?
3366 maybe an exitWith handler?
3370 Some of these virtual ``registers'' are used very frequently and should
3371 be mapped onto machine registers if at all possible. Others are used
3372 very infrequently and can be kept in memory to free up registers for
3375 On register-poor architectures, we can play a few tricks to reduce the
3376 number of virtual registers which need to be accessed on a regular
3381 - Grow stack and heap towards each other (single-threaded system only)
3382 - We might need to keep the C stack pointer in a register if that
3383 is what the OS expects when a signal occurs.
3384 - Preemption flag trick
3385 - If any of the frequently accessed registers cannot be mapped onto
3386 machine registers we should keep the TSO in a machine register to
3387 allow faster access to all the other non-machine registers.