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{\Note}[1]{{{\bf Note:}\sl #1}}
48 \newcommand{\Arg}[1]{\mbox{${\tt arg}_{#1}$}}
49 \newcommand{\bottom}{bottom} % foo, can't remember the symbol name
51 \title{The STG runtime system (revised)}
52 \author{Simon Peyton Jones \\ Glasgow University and Oregon Graduate Institute \and
53 Simon Marlow \\ Glasgow University \and
54 Alastair Reid \\ Yale University}
64 This document describes the GHC/Hugs run-time system. It serves as
65 a Glasgow/Yale/Nottingham ``contract'' about what the RTS does.
67 \subsection{New features compared to GHC 2.04}
70 \item The RTS supports mixed compiled/interpreted execution, so
71 that a program can consist of a mixture of GHC-compiled and Hugs-interpreted
74 \item CAFs are only retained if they are
75 reachable. Since they are referred to by implicit references buried
76 in code, this means that the garbage collector must traverse the whole
77 accessible code tree. This feature eliminates a whole class of painful
80 \item A running thread has only one stack, which contains a mixture
81 of pointers and non-pointers. Section~\ref{sect:stacks} describes how
82 we find out which is which. (GHC has used two stacks for some while.
83 Using one stack instead of two reduces register pressure, reduces the
84 size of update frames, and eliminates
85 ``stack-stubbing'' instructions.)
87 \item The ``return in registers'' return convention has been dropped
88 because it was complicated and doesn't work well on register-poor
89 architectures. It has been partly replaced by unboxed tuples
90 (section~\ref{sect:unboxed-tuples}) which allow the programmer to
91 explicitly state where results should be returned in registers (or on
92 the stack) instead of on the heap.
96 \subsection{Wish list}
98 Here's a list of things we'd like to support in the future.
100 \item Interrupts, speculative computation.
103 The SM could tune the size of the allocation arena, the number of
104 generations, etc taking into account residency, GC rate and page fault
108 There should be no need to specify the amnount of stack/heap space to
109 allocate when you started a program - let it just take as much or as
110 little as it wants. (It might be useful to be able to specify maximum
111 sizes and to be able to suggest an initial size.)
114 We could trigger a GC when all threads are blocked waiting for IO if
115 the allocation arena (or some of the generations) are nearly full.
119 \subsection{Configuration}
121 Some of the above features are expensive or less portable, so we
122 envision building a number of different configurations supporting
123 different subsets of the above features.
125 You can make the following choices:
128 Support for concurrency or parallelism. There are four
129 mutually-exclusive choices.
132 \item[@SEQUENTIAL@] No concurrency or parallelism support.
133 This configuration might not support interrupt recovery.
134 \item[@CONCURRENT@] Support for concurrency but not for parallelism.
135 \item[@CONCURRENT@+@GRANSIM@] Concurrency support and simulated parallelism.
136 \item[@CONCURRENT@+@PARALLEL@] Concurrency support and real parallelism.
139 \item @PROFILING@ adds cost-centre profiling.
141 \item @TICKY@ gathers internal statistics (often known as ``ticky-ticky'' code).
143 \item @DEBUG@ does internal consistency checks.
145 \item Persistence. (well, not yet).
148 Which garbage collector to use. At the moment we
149 only anticipate one, however.
152 \subsection{Glossary}
154 \ToDo{This terminology is not used consistently within the document.
155 If you find something which disagrees with this terminology, fix the
160 \item A {\em word} is (at least) 32 bits and can hold either a signed
163 \item A {\em pointer} is (at least) 32 bits and big enough to hold a
164 function pointer or a data pointer.
166 \item A {\em boxed} type is one whose elements are heap allocated.
168 \item An {\em unboxed} type is one whose elements are {\em not} heap allocated.
170 \item A {\em pointed} type is one that contains $\bot$. Variables with
171 pointed types are the only things which can be lazily evaluated. In
172 the STG machine, this means that they are the only things that can be
173 {\em entered} or {\em updated} and it requires that they be boxed.
175 \item An {\em unpointed} type is one that does not contains $\bot$.
176 Variables with unpointed types are never delayed --- they are always
177 evaluated when they are constructed. In the STG machine, this means
178 that they cannot be {\em entered} or {\em updated}. Unpointed objects
179 may be boxed (like @Array#@) or unboxed (like @Int#@).
181 \item A {\em closure} is a (representation of) a value of a {\em pointed}
182 type. It may be in HNF or it may be unevaluated --- in either case, you can
183 try to evaluate it again.
185 \item A {\em thunk} is a (representation of) a value of a {\em pointed}
186 type which is {\em not} in HNF.
188 \item A {\em value} is an object in HNF. It can be pointed or unpointed.
192 Occasionally, a field of a data structure must hold either a word or a
193 pointer. In such circumstances, it is {\em not safe} to assume that
194 words and pointers are the same size.
197 % More terminology to mention.
200 \subsection{Subtle Dependencies}
202 Some decisions have very subtle consequences which should be written
203 down in case we want to change our minds.
207 \item The garbage collector never expands an object when it promotes
208 it to the old generation. This is important because the GC avoids
209 performing heap overflow checks by assuming that the amount added to
210 the old generation is no bigger than the current new generation.
214 If the garbage collector is allowed to shrink the stack of a thread,
215 we cannot omit the stack check in return continuations
216 (section~\ref{sect:heap-and-stack-checks}).
220 When we return to the scheduler, the top object on the stack is a closure.
221 The scheduler restarts the thread by entering the closure.
223 Section~\ref{sect:hugs-return-convention} discusses how Hugs returns an
224 unboxed value to GHC and how GHC returns an unboxed value to Hugs.
228 When we return to the scheduler, we need a few empty words on the stack
229 to store a closure to reenter. Section~\ref{sect:heap-and-stack-checks}
230 discusses who does the stack check and how much space they need.
234 Heap objects never contain slop --- this is required if we want to
235 support mostly-copying garbage collection.
237 This is hard to arrange if we do \emph{lazy} blackholing
238 (section~\ref{sect:lazy-black-holing}) so we currently plan to
239 blackhole an object when we push the update frame.
243 Info tables for constructors contain enough information to decide which
244 return convention they use. This allows Hugs to use a single piece of
245 entry code for all constructors and insulates Hugs from changes in the
246 choice of return convention.
250 \section{Source Language}
252 \subsection{Explicit Allocation}\label{sect:explicit-allocation}
254 As in the original STG machine, (almost) all heap allocation is caused
255 by executing a let(rec). Since we no longer support the return in
256 registers convention for data constructors, constructors now cause heap
257 allocation and so they should be let-bound.
259 For example, we now write
261 > cons = \ x xs -> let r = (:) x xs in r
265 > cons = \ x xs -> (:) x xs
269 \subsection{Unboxed tuples}\label{sect:unboxed-tuples}
271 \Note{We're not planning to implement this right away. There doesn't
272 seem to be any real difficulty adding it to the runtime system but
273 it'll take a lot of work adding it to the compiler. Since unboxed
274 tuples do not trigger allocation, the syntax could be modified to allow
275 unboxed tuples in expressions.}
277 Functions can take multiple arguments as easily as they can take one
278 argument: there's no cost for adding another argument. But functions
279 can only return one result: the cost of adding a second ``result'' is
280 that the function must construct a tuple of ``results'' on the heap.
281 The assymetry is rather galling and can make certain programming
282 styles quite expensive. For example, consider a simple state transformer
285 > type S a = State -> (a,State)
286 > bindS m k s0 = case m s0 of { (a,s1) -> k a s1 }
287 > returnS a s = (a,s)
291 Here, every use of @returnS@, @getS@ or @setS@ constructs a new tuple
292 in the heap which is instantly taken apart (and becomes garbage) by
293 the case analysis in @bind@. Even a short state-transformer program
294 will construct a lot of these temporary tuples.
296 Unboxed tuples provide a way for the programmer to indicate that they
297 do not expect a tuple to be shared and that they do not expect it to
298 be allocated in the heap. Syntactically, unboxed tuples are just like
299 single constructor datatypes except for the annotation @unboxed@.
301 > data unboxed AAndState# a = AnS a State
302 > type S a = State -> AAndState# a
303 > bindS m k s0 = case m s0 of { AnS a s1 -> k a s1 }
304 > returnS a s = AnS a s
306 > setS s _ = AnS () s
308 Semantically, unboxed tuples are just unlifted tuples and are subject
309 to the same restrictions as other unpointed types.
311 Operationally, unboxed tuples are never built on the heap. When
312 unboxed tuples are returned, they are returned in multiple registers
313 or multiple stack slots. At first sight, this seems a little strange
314 but it's no different from passing double precision floats in two
317 Note that unboxed tuples can only have one constructor and that
318 thunks never have unboxed types --- so we'll never try to update an
319 unboxed constructor. The restriction to a single constructor is
320 largely to avoid garbage collection complications.
322 \subsection{STG Syntax}
324 \ToDo{Insert STG syntax with appropriate changes.}
327 %-----------------------------------------------------------------------------
328 \part{Evaluation Model}
332 This part is concerned with defining the external interfaces of the
333 major components of the system; the next part is concerned with their
336 The major components of the system are:
340 \item The storage manager
341 \item The machine code evaluator (compiled code)
342 \item The bytecode evaluator (interpreted code)
346 \section{The Compilers}
348 Need to describe interface files.
350 Here's an example - but I don't know the grammar - ADR.
356 1 main _:_ IOBase.IO PrelBase.();;
359 \section{The Scheduler}
361 The Scheduler is the heart of the run-time system. A running program
362 consists of a single running thread, and a list of runnable and
363 blocked threads. The running thread returns to the scheduler when any
364 of the following conditions arises:
367 \item A heap check fails, and a garbage collection is required
368 \item Compiled code needs to switch to interpreted code, and vice
370 \item The thread becomes blocked.
371 \item The thread is preempted.
374 A running system has a global state, consisting of
377 \item @Hp@, the current heap pointer, which points to the next
378 available address in the Heap.
379 \item @HpLim@, the heap limit pointer, which points to the end of the
381 \item The Thread Preemption Flag, which is set whenever the currently
382 running thread should be preempted at the next opportunity.
383 \item A list of runnable threads.
384 \item A list of blocked threads.
387 Each thread is represented by a Thread State Object (TSO), which is
388 described in detail in Section \ref{sect:TSO}.
390 The following is pseudo-code for the inner loop of the scheduler
394 while (threads_exist) {
395 // handle global problems: GC, parallelism, etc
397 if (external_message) service_message();
398 // deal with other urgent stuff
400 pick a runnable thread;
402 // enter object on top of stack
403 // if the top object is a BCO, we must enter it
404 // otherwise appply any heuristic we wish.
405 if (thread->stack[thread->sp]->info.type == BCO) {
406 status = runHugs(thread,&smInfo);
408 status = runGHC(thread,&smInfo);
410 switch (status) { // handle local problems
411 case (StackOverflow): enlargeStack; break;
412 case (Error e) : error(thread,e); break;
413 case (ExitWith e) : exit(e); break;
414 case (Yield) : break;
416 } while (thread_runnable);
420 \subsection{Invoking the garbage collector}
421 \subsection{Putting the thread to sleep}
423 \subsection{Calling C from Haskell}
425 We distinguish between "safe calls" where the programmer guarantees
426 that the C function will not call a Haskell function or, in a
427 multithreaded system, block for a long period of time and "unsafe
428 calls" where the programmer cannot make that guarantee.
430 Safe calls are performed without returning to the scheduler and are
431 discussed elsewhere (\ToDo{discuss elsewhere}).
433 Unsafe calls are performed by returning an array (outside the Haskell
434 heap) of arguments and a C function pointer to the scheduler. The
435 scheduler allocates a new thread from the operating system
436 (multithreaded system only), spawns a call to the function and
437 continues executing another thread. When the ccall completes, the
438 thread informs the scheduler and the scheduler adds the thread to the
439 runnable threads list.
441 \ToDo{Describe this in more detail.}
444 \subsection{Calling Haskell from C}
446 When C calls a Haskell closure, it sends a message to the scheduler
447 thread. On receiving the message, the scheduler creates a new Haskell
448 thread, pushes the arguments to the C function onto the thread's stack
449 (with tags for unboxed arguments) pushes the Haskell closure and adds
450 the thread to the runnable list so that it can be entered in the
453 When the closure returns, the scheduler sends back a message which
454 awakens the (C) thread.
456 \ToDo{Do we need to worry about the garbage collector deallocating the
457 thread if it gets blocked?}
459 \subsection{Switching Worlds}
460 \label{sect:switching-worlds}
462 \ToDo{This has all changed: we always leave a closure on top of the
463 stack if we mean to continue executing it. The scheduler examines the
464 top of the stack and tries to guess which world we want to be in. If
465 it finds a @BCO@, it certainly enters Hugs, if it finds a @GHC@
466 closure, it certainly enters GHC and if it finds a standard closure,
467 it is free to choose either one but it's probably best to enter GHC
468 for everything except @BCO@s and perhaps @AP@s.}
470 Because this is a combined compiled/interpreted system, the
471 interpreter will sometimes encounter compiled code, and vice-versa.
473 All world-switches go via the scheduler, ensuring that the world is in
474 a known state ready to enter either compiled code or the interpreter.
475 When a thread is run from the scheduler, the @whatNext@ field in the
476 TSO (Section \ref{sect:TSO}) is checked to find out how to execute the
480 \item If @whatNext@ is set to @ReturnGHC@, we load up the required
481 registers from the TSO and jump to the address at the top of the user
483 \item If @whatNext@ is set to @EnterGHC@, we load up the required
484 registers from the TSO and enter the closure pointed to by the top
486 \item If @whatNext@ is set to @EnterHugs@, we enter the top thing on
487 the stack, using the interpreter.
490 There are four cases we need to consider:
493 \item A GHC thread enters a Hugs-built closure.
494 \item A GHC thread returns to a Hugs-compiled return address.
495 \item A Hugs thread enters a GHC-built closure.
496 \item A Hugs thread returns to a Hugs-compiled return address.
499 GHC-compiled modules cannot call functions in a Hugs-compiled module
500 directly, because the compiler has no information about arities in the
501 external module. Therefore it must assume any top-level objects are
502 CAFs, and enter their closures.
504 \ToDo{Hugs-built constructors?}
506 We now examine the various cases one by one and describe how the
507 switch happens in each situation.
509 \subsection{A GHC thread enters a Hugs-built closure}
510 \label{sect:ghc-to-hugs-closure}
512 There is three possibilities: GHC has entered a @PAP@, or it has
513 entered a @AP@, or it has entered the BCO directly (for a top-level
514 function closure). @AP@s and @PAP@s are ``standard closures'' and
515 so do not require us to enter the bytecode interpreter.
517 The entry code for a BCO does the following:
520 \item Push the address of the object entered on the stack.
521 \item Save the current state of the thread in its TSO.
522 \item Return to the scheduler, setting @whatNext@ to @EnterHugs@.
525 BCO's for thunks and functions have the same entry conventions as
526 slow entry points: they expect to find their arguments on the stac
527 with unboxed arguments preceded by appropriate tags.
529 \subsection{A GHC thread returns to a Hugs-compiled return address}
530 \label{sect:ghc-to-hugs-return}
532 Hugs return addresses are laid out as in Figure
533 \ref{fig:hugs-return-stack}. If GHC is returning, it will return to
534 the address at the top of the stack, namely @HUGS_RET@. The code at
535 @HUGS_RET@ performs the following:
538 \item pushes \Arg{1} (the return value) on the stack.
539 \item saves the thread state in the TSO
540 \item returns to the scheduler with @whatNext@ set to @EnterHugs@.
543 \noindent When Hugs runs, it will enter the return value, which will
544 return using the correct Hugs convention (Section
545 \ref{sect:hugs-return-convention}) to the return address underneath it
548 \subsection{A Hugs thread enters a GHC-compiled closure}
549 \label{sect:hugs-to-ghc-closure}
551 Hugs can recognise a GHC-built closure as not being one of the
552 following types of object:
558 \item An indirection, or
562 When Hugs is called on to enter a GHC closure, it executes the
563 following sequence of instructions:
566 \item Push the address of the closure on the stack.
567 \item Save the current state of the thread in the TSO.
568 \item Return to the scheduler, with the @whatNext@ field set to
572 \subsection{A Hugs thread returns to a GHC-compiled return address}
573 \label{sect:hugs-to-ghc-return}
575 When Hugs encounters a return address on the stack that is not
576 @HUGS_RET@, it knows that a world-switch is required. At this point
577 the stack contains a pointer to the return value, followed by the GHC
578 return address. The following sequence is then performed:
581 \item save the state of the thread in the TSO.
582 \item return to the scheduler, setting @whatNext@ to @EnterGHC@.
585 The first thing that GHC will do is enter the object on the top of the
586 stack, which is a pointer to the return value. This value will then
587 return itself to the return address using the GHC return convention.
591 \ToDo{Is it ok to load code when threads are running?}
593 In a batch mode system, we can statically link all the modules
594 together. In an interactive system we need a loader which will
595 explicitly load and unload individual modules (or, perhaps, blocks of
596 mutually dependent modules) and resolve references between modules.
598 While many operating systems provide support for dynamic loading and
599 will automatically resolve cross-module references for us, we generally
600 cannot rely on being able to load mutually dependent modules.
602 A portable solution is to perform some of the linking ourselves. Each module
603 should provide three global symbols:
606 An initialisation routine. (Might also be used for finalisation.)
608 A table of symbols it exports.
609 Entries in this table consist of the symbol name and the address of the
612 A table of symbols it imports.
613 Entries in this table consist of the symbol name and a list of references
617 On loading a group of modules, the loader adds the contents of the
618 export lists to a symbol table and then fills in all the references in the
621 References in import lists are of two types:
623 \item[ References in machine code ]
625 The most efficient approach is to patch the machine code directly, but
626 this will be a lot of work, very painful to port and rather fragile.
628 Alternatively, the loader could store the value of each symbol in the
629 import table for each module and the compiled code can access all
630 external objects through the import table. This requires that the
631 import table be writable but does not require that the machine code or
632 info tables be writable.
634 \item[ References in data structures (SRTs and static data constructors) ]
636 Either we patch the SRTs and constructors directly or we somehow use
637 indirections through the symbol table. Patching the SRTs requires
638 that we make them writable and prevents us from making effective use
639 of virtual memories that use copy-on-write policies. Using an
640 indirection is possible but tricky.
642 Note: We could avoid patching machine code if all references to
643 eternal references went through the SRT --- then we just have one
644 thing to patch. But the SRT always contains a pointer to the closure
645 rather than the fast entry point (say), so we'd take a big performance
650 \section{Compiled Execution}
652 This section describes the framework in which compiled code evaluates
653 expressions. Only at certain points will compiled code need to be
654 able to talk to the interpreted world; these are discussed in Section
655 \ref{sect:switching-worlds}.
657 \subsection{Calling conventions}
659 \subsubsection{The call/return registers}
661 One of the problems in designing a virtual machine is that we want it
662 abstract away from tedious machine details but still reveal enough of
663 the underlying hardware that we can make sensible decisions about code
664 generation. A major problem area is the use of registers in
665 call/return conventions. On a machine with lots of registers, it's
666 cheaper to pass arguments and results in registers than to pass them
667 on the stack. On a machine with very few registers, it's cheaper to
668 pass arguments and results on the stack than to use ``virtual
669 registers'' in memory. We therefore use a hybrid system: the first
670 $n$ arguments or results are passed in registers; and the remaining
671 arguments or results are passed on the stack. For register-poor
672 architectures, it is important that we allow $n=0$.
674 We'll label the arguments and results \Arg{1} \ldots \Arg{m} --- with
675 the understanding that \Arg{1} \ldots \Arg{n} are in registers and
676 \Arg{n+1} \ldots \Arg{m} are on top of the stack.
678 Note that the mapping of arguments \Arg{1} \ldots \Arg{n} to machine
679 registers depends on the {\em kinds} of the arguments. For example,
680 if the first argument is a Float, we might pass it in a different
681 register from if it is an Int. In fact, we might find that a given
682 architecture lets us pass varying numbers of arguments according to
683 their types. For example, if a CPU has 2 Int registers and 2 Float
684 registers then we could pass between 2 and 4 arguments in machine
685 registers --- depending on whether they all have the same kind or they
686 have different kinds.
688 \subsubsection{Entering closures}
689 \label{sect:entering-closures}
691 To evaluate a closure we jump to the entry code for the closure
692 passing a pointer to the closure in \Arg{1} so that the entry code can
693 access its environment.
695 \subsubsection{Function call}
697 The function-call mechanism is obviously crucial. There are five different
701 \item {\em Known combinator (function with no free variables) and enough arguments.}
703 A fast call can be made: push excess arguments onto stack and jump to
704 function's {\em fast entry point} passing arguments in \Arg{1} \ldots
707 The {\em fast entry point} is only called with exactly the right
708 number of arguments (in \Arg{1} \ldots \Arg{m}) so it can instantly
709 start doing useful work without first testing whether it has enough
710 registers or having to pop them off the stack first.
712 \item {\em Known combinator and insufficient arguments.}
714 A slow call can be made: push all arguments onto stack and jump to
715 function's {\em slow entry point}.
717 Any unpointed arguments which are pushed on the stack must be tagged.
718 This means pushing an extra word on the stack below the unpointed
719 words, containing the number of unpointed words above it.
721 %Todo: forward ref about tagging?
724 The {\em slow entry point} might be called with insufficient arguments
725 and so it must test whether there are enough arguments on the stack.
726 This {\em argument satisfaction check} consists of checking that
727 @Su-Sp@ is big enough to hold all the arguments (including any tags).
731 \item If the argument satisfaction check fails, it is because there is
732 one or more update frames on the stack before the rest of the
733 arguments that the function needs. In this case, we construct a PAP
734 (partial application, section~\ref{sect:PAP}) containing the arguments
735 which are on the stack. The PAP construction code will return to the
736 update frame with the address of the PAP in \Arg{1}.
738 \item If the argument satisfaction check succeeds, we jump to the fast
739 entry point with the arguments in \Arg{1} \ldots \Arg{arity}.
741 If the fast entry point expects to receive some of \Arg{i} on the
742 stack, we can reduce the amount of movement required by making the
743 stack layout for the fast entry point look like the stack layout for
744 the slow entry point. Since the slow entry point is entered with the
745 first argument on the top of the stack and with tags in front of any
746 unpointed arguments, this means that if \Arg{i} is unpointed, there
747 should be space below it for a tag and that the highest numbered
748 argument should be passed on the top of the stack.
750 We usually arrange that the fast entry point is placed immediately
751 after the slow entry point --- so we can just ``fall through'' to the
752 fast entry point without performing a jump.
757 \item {\em Known function closure (function with free variables) and enough arguments.}
759 A fast call can be made: push excess arguments onto stack and jump to
760 function's {\em fast entry point} passing a pointer to closure in
761 \Arg{1} and arguments in \Arg{2} \ldots \Arg{m+1}.
763 Like the fast entry point for a combinator, the fast entry point for a
764 closure is only called with appropriate values in \Arg{1} \ldots
765 \Arg{m+1} so we can start work straight away. The pointer to the
766 closure is used to access the free variables of the closure.
769 \item {\em Known function closure and insufficient arguments.}
771 A slow call can be made: push all arguments onto stack and jump to the
772 closure's slow entry point passing a pointer to the closure in \Arg{1}.
774 Again, the slow entry point performs an argument satisfaction check
775 and either builds a PAP or pops the arguments off the stack into
776 \Arg{2} \ldots \Arg{m+1} and jumps to the fast entry point.
779 \item {\em Unknown function closure, thunk or constructor.}
781 Sometimes, the function being called is not statically identifiable.
782 Consider, for example, the @compose@ function:
784 compose f g x = f (g x)
786 Since @f@ and @g@ are passed as arguments to @compose@, the latter has
787 to make a heap call. In a heap call the arguments are pushed onto the
788 stack, and the closure bound to the function is entered. In the
789 example, a thunk for @(g x)@ will be allocated, (a pointer to it)
790 pushed on the stack, and the closure bound to @f@ will be
791 entered. That is, we will jump to @f@s entry point passing @f@ in
792 \Arg{1}. If \Arg{1} is passed on the stack, it is pushed on top of
793 the thunk for @(g x)@.
795 The {\em entry code} for an updateable thunk (which must have arity 0)
796 pushes an update frame on the stack and starts executing the body of
797 the closure --- using \Arg{1} to access any free variables. This is
798 described in more detail in section~\ref{sect:data-updates}.
800 The {\em entry code} for a non-updateable closure is just the
801 closure's slow entry point.
805 In addition to the above considerations, if there are \emph{too many}
806 arguments then the extra arguments are simply pushed on the stack with
809 To summarise, a closure's standard (slow) entry point performs the following:
811 \item[Argument satisfaction check.] (function closure only)
812 \item[Stack overflow check.]
813 \item[Heap overflow check.]
814 \item[Copy free variables out of closure.] %Todo: why?
815 \item[Eager black holing.] (updateable thunk only) %Todo: forward ref.
816 \item[Push update frame.]
817 \item[Evaluate body of closure.]
821 \subsection{Case expressions and return conventions}
822 \label{sect:return-conventions}
824 The {\em evaluation} of a thunk is always initiated by
825 a @case@ expression. For example:
830 The code for a @case@ expression looks like this:
833 \item Push the free variables of the branches on the stack (fv(@E@) in
835 \item Push a \emph{return address} on the stack.
836 \item Evaluate the scrutinee (@x@ in this case).
839 Once evaluation of the scrutinee is complete, execution resumes at the
840 return address, which points to the code for the expression @E@.
842 When execution resumes at the return point, there must be some {\em
843 return convention} that defines where the components of the pair, @a@
844 and @b@, can be found. The return convention varies according to the
845 type of the scrutinee @x@:
851 (A space for) the return address is left on the top of the stack.
852 Leaving the return address on the stack ensures that the top of the
853 stack contains a valid activation record
854 (section~\ref{sect:activation-records}) --- should a garbage collection
857 \item If @x@ has a boxed type (e.g.~a data constructor or a function),
858 a pointer to @x@ is returned in \Arg{1}.
860 \ToDo{Warn that components of E should be extracted as soon as
861 possible to avoid a space leak.}
863 \item If @x@ is an unboxed type (e.g.~@Int#@ or @Float#@), @x@ is
866 \item If @x@ is an unboxed tuple constructor, the components of @x@
867 are returned in \Arg{1} \ldots \Arg{n} but no object is constructed in
870 When passing an unboxed tuple to a function, the components are
871 flattened out and passed in \Arg{1} \ldots \Arg{n} as usual.
875 \subsection{Vectored Returns}
877 Many algebraic data types have more than one constructor. For
878 example, the @Maybe@ type is defined like this:
880 data Maybe a = Nothing | Just a
882 How does the return convention encode which of the two constructors is
883 being returned? A @case@ expression scrutinising a value of @Maybe@
884 type would look like this:
890 Rather than pushing a return address before evaluating the scrutinee,
891 @E@, the @case@ expression pushes (a pointer to) a {\em return
892 vector}, a static table consisting of two code pointers: one for the
893 @Just@ alternative, and one for the @Nothing@ alternative.
899 The constructor @Nothing@ returns by jumping to the first item in the
900 return vector with a pointer to a (statically built) Nothing closure
903 It might seem that we could avoid loading \Arg{1} in this case since the
904 first item in the return vector will know that @Nothing@ was returned
905 (and can easily access the Nothing closure in the (unlikely) event
906 that it needs it. The only reason we load \Arg{1} is in case we have to
907 perform an update (section~\ref{sect:data-updates}).
911 The constructor @Just@ returns by jumping to the second element of the
912 return vector with a pointer to the closure in \Arg{1}.
916 In this way no test need be made to see which constructor returns;
917 instead, execution resumes immediately in the appropriate branch of
920 \subsection{Direct Returns}
922 When a datatype has a large number of constructors, it may be
923 inappropriate to use vectored returns. The vector tables may be
924 large and sparse, and it may be better to identify the constructor
925 using a test-and-branch sequence on the tag. For this reason, we
926 provide an alternative return convention, called a \emph{direct
929 In a direct return, the return address pushed on the stack really is a
930 code pointer. The returning code loads a pointer to the closure being
931 returned in \Arg{1} as usual, and also loads the tag into \Arg{2}.
932 The code at the return address will test the tag and jump to the
933 appropriate code for the case branch.
935 The choice of whether to use a vectored return or a direct return is
936 made on a type-by-type basis --- up to a certain maximum number of
937 constructors imposed by the update mechanism
938 (section~\ref{sect:data-updates}).
940 Single-constructor data types also use direct returns, although in
941 that case there is no need to return a tag in \Arg{2}.
943 \ToDo{Say whether we pop the return address before returning}
945 \ToDo{Stack stubbing?}
948 \label{sect:data-updates}
950 The entry code for an updatable thunk (which must be of arity 0):
953 \item copies the free variables out of the thunk into registers or
955 \item pushes an {\em update frame} onto the stack.
957 An update frame is a small activation record consisting of
959 \begin{tabular}{|l|l|l|}
961 {\em Fixed header} & {\em Update Frame link} & {\em Updatee} \\
966 \note{In the semantics part of the STG paper (section 5.6), an update
967 frame consists of everything down to the last update frame on the
968 stack. This would make sense too --- and would fit in nicely with
969 what we're going to do when we add support for speculative
971 \ToDo{I think update frames contain cost centres sometimes}
974 If we are doing ``eager blackholing,'' we then overwrite the thunk
975 with a black hole. Otherwise, we leave it to the garbage collector to
976 black hole the thunk.
979 Start evaluating the body of the expression.
983 When the expression finishes evaluation, it will enter the update
984 frame on the top of the stack. Since the returner doesn't know
985 whether it is entering a normal return address/vector or an update
986 frame, we follow exactly the same conventions as return addresses and
987 return vectors. That is, on entering the update frame:
990 \item The value of the thunk is in \Arg{1}. (Recall that only thunks
991 are updateable and that thunks return just one value.)
993 \item If the data type is a direct-return type rather than a
994 vectored-return type, then the tag is in \Arg{2}.
996 \item The update frame is still on the stack.
999 We can safely share a single statically-compiled update function
1000 between all types. However, the code must be able to handle both
1001 vectored and direct-return datatypes. This is done by arranging that
1002 the update code looks like this:
1010 |---------------| <- update code pointer
1015 Each entry in the return vector (which is large enough to cover the
1016 largest vectored-return type) points to the update code.
1020 \item overwrites the {\em updatee} with an indirection to \Arg{1};
1021 \item loads @Su@ from the Update Frame link;
1022 \item removes the update frame from the stack; and
1023 \item enters \Arg{1}.
1026 We enter \Arg{1} again, having probably just come from there, because
1027 it knows whether to perform a direct or vectored return. This could
1028 be optimised by compiling special update code for each slot in the
1029 return vector, which performs the correct return.
1031 \subsection{Semi-tagging}
1032 \label{sect:semi-tagging}
1034 When a @case@ expression evaluates a variable that might be bound
1035 to a thunk it is often the case that the scrutinee is already evaluated.
1036 In this case we have paid the penalty of (a) pushing the return address (or
1037 return vector address) on the stack, (b) jumping through the info pointer
1038 of the scrutinee, and (c) returning by an indirect jump through the
1039 return address on the stack.
1041 If we knew that the scrutinee was already evaluated we could generate
1042 (better) code which simply jumps to the appropriate branch of the
1043 @case@ with a pointer to the scrutinee in \Arg{1}. (For direct
1044 returns to multiconstructor datatypes, we might also load the tag into
1047 An obvious idea, therefore, is to test dynamically whether the heap
1048 closure is a value (using the tag in the info table). If not, we
1049 enter the closure as usual; if so, we jump straight to the appropriate
1050 alternative. Here, for example, is pseudo-code for the expression
1051 @(case x of { (a,_,c) -> E }@:
1053 \Arg{1} = <pointer to x>;
1054 tag = \Arg{1}->entry->tag;
1056 Sp--; \\ insert space for return address
1060 goto \Arg{1}->entry;
1062 <info table for return address goes here>
1063 ret: a = \Arg{1}->data1; \\ suck out a and c to avoid space leak
1067 and here is the code for the expression @(case x of { [] -> E1; x:xs -> E2 }@:
1069 \Arg{1} = <pointer to x>;
1070 tag = \Arg{1}->entry->tag;
1072 Sp--; \\ insert space for return address
1076 goto \Arg{1}->entry;
1080 retvec: \\ reversed return vector
1081 <return info table for case goes here>
1083 panic("Direct return into vectored case");
1087 ret2: x = \Arg{1}->head;
1091 There is an obvious cost in compiled code size (but none in the size
1092 of the bytecodes). There is also a cost in execution time if we enter
1093 more thunks than data constructors.
1095 Both the direct and vectored returns are easily modified to chase chains
1096 of indirections too. In the vectored case, this is most easily done by
1097 making sure that @IND = TAG_1 - 1@, and adding an extra field to every
1098 return vector. In the above example, the indirection code would be
1100 ind: \Arg{1} = \Arg{1}->next;
1103 where @ind_loop@ is the second line of code.
1105 Note that we have to leave space for a return address since the return
1106 address expects to find one. If the body of the expression requires a
1107 heap check, we will actually have to write the return address before
1108 entering the garbage collector.
1111 \subsection{Heap and Stack Checks}
1112 \label{sect:heap-and-stack-checks}
1114 The storage manager detects that it needs to garbage collect the old
1115 generation when the evaluator requests a garbage collection without
1116 having moved the heap pointer since the last garbage collection. It
1117 is therefore important that the GC routines {\em not} move the heap
1118 pointer unless the heap check fails. This is different from what
1119 happens in the current STG implementation.
1121 Assuming that the stack can never shrink, we perform a stack check
1122 when we enter a closure but not when we return to a return
1123 continuation. This doesn't work for heap checks because we cannot
1124 predict what will happen to the heap if we call a function.
1126 If we wish to allow the stack to shrink, we need to perform a stack
1127 check whenever we enter a return continuation. Most of these checks
1128 could be eliminated if the storage manager guaranteed that a stack
1129 would always have 1000 words (say) of space after it was shrunk. Then
1130 we can omit stack checks for less than 1000 words in return
1133 When an argument satisfaction check fails, we need to push the closure
1134 (in R1) onto the stack - so we need to perform a stack check. The
1135 problem is that the argument satisfaction check occurs \emph{before}
1136 the stack check. The solution is that the caller of a slow entry
1137 point or closure will guarantee that there is at least one word free
1138 on the stack for the callee to use.
1140 Similarily, if a heap or stack check fails, we need to push the arguments
1141 and closure onto the stack. If we just came from the slow entry point,
1142 there's certainly enough space and it is the responsibility of anyone
1143 using the fast entry point to guarantee that there is enough space.
1145 \ToDo{Be more precise about how much space is required - document it
1146 in the calling convention section.}
1148 \subsection{Handling interrupts/signals}
1151 May have to keep C stack pointer in register to placate OS?
1152 May have to revert black holes - ouch!
1155 \section{Interpreted Execution}
1157 This section describes how the Hugs interpreter interprets code in the
1158 same environment as compiled code executes. Both evaluation models
1159 use a common garbage collector, so they must agree on the form of
1160 objects in the heap.
1162 Hugs interprets code by converting it to byte-code and applying a
1163 byte-code interpreter to it. Wherever possible, we try to ensure that
1164 the byte-code is all that is required to interpret a section of code.
1165 This means not dynamically generating info tables, and hence we can
1166 only have a small number of possible heap objects each with a statically
1167 compiled info table. Similarly for stack objects: in fact we only
1168 have one Hugs stack object, in which all information is tagged for the
1171 There is, however, one exception to this rule. Hugs must generate
1172 info tables for any constructors it is asked to compile, since the
1173 alternative is to force a context-switch each time compiled code
1174 enters a Hugs-built constructor, which would be prohibitively
1177 We achieve this simplicity by forgoing some of the optimisations used
1182 Whereas compiled code has five different ways of entering a closure
1183 (section~\ref{sect:entering-closures}), interpreted code has only one.
1184 The entry point for interpreted code behaves like slow entry points for
1189 We use just one info table for {\em all\/} direct returns.
1190 This introduces two problems:
1192 \item How does the interpreter know what code to execute?
1194 Instead of pushing just a return address, we push a return BCO and a
1195 trivial return address which just enters the return BCO.
1197 (In a purely interpreted system, we could avoid pushing the trivial
1200 \item How can the garbage collector follow pointers within the
1203 We could push a third word ---a bitmask describing the location of any
1204 pointers within the record--- but, since we're already tagging unboxed
1205 function arguments on the stack, we use the same mechanism for unboxed
1206 values within the activation record.
1208 \ToDo{Do we have to stub out dead variables in the activation frame?}
1214 We trivially support vectored returns by pushing a return vector whose
1215 entries are all the same.
1219 We avoid the need to build SRTs by putting bytecode objects on the
1220 heap and restricting BCOs to a single basic block.
1224 \subsubsection{Hugs Info Tables}
1226 Hugs requires the following info tables and closures:
1230 Contains both a vectored return table and a direct entry point. All
1231 entry points are the same: they rearrange the stack to match the Hugs
1232 return convention (section~{sect:hugs-return-convention}) and return
1233 to the scheduler. When the scheduler restarts the thread, it will
1234 find a BCO on top of the stack and will enter the Hugs interpreter.
1238 \item [Constructors].
1240 The entry code for a constructor jumps to a generic entry point in the
1241 runtime system which decides whether to do a vectored or unvectored
1242 return depending on the shape of the constructor/type. This implies that
1243 info tables must have enough info to make that decision.
1245 \item [@AP@ and @PAP@].
1247 \item [Indirections].
1251 -- doesn't generate them itself but it ought to recognise them
1253 \item [Complex primops].
1258 \subsection{Hugs Heap Objects}
1259 \label{sect:hugs-heap-objects}
1261 \subsubsection{Byte-Code Objects}
1263 Compiled byte code lives on the global heap, in objects called
1264 Byte-Code Objects (or BCOs). The layout of BCOs is described in
1265 detail in Section \ref{sect:BCO}, in this section we will describe
1268 Since byte-code lives on the heap, it can be garbage collected just
1269 like any other heap-resident data. Hugs arranges that any BCO's
1270 referred to by the Hugs symbol tables are treated as live objects by
1271 the garbage collectr. When a module is unloaded, the pointers to its
1272 BCOs are removed from the symbol table, and the code will be garbage
1273 collected some time later.
1275 A BCO represents a basic block of code - all entry points are at the
1276 beginning of a BCO, and it is impossible to jump into the middle of
1277 one. A BCO represents not only the code for a function, but also its
1278 closure; a BCO can be entered just like any other closure. Hugs
1279 performs lambda-lifting during compilation to byte-code, and each
1280 top-level combinator becomes a BCO in the heap.
1282 \ToDo{The phrase "all entry points..." suggests that BCOs have multiple
1283 entry points. If so, we need to say a lot more about it...}
1285 \subsubsection{Thunks and partial applications}
1287 A thunk consists of a code pointer, and values for the free variables
1288 of that code. Since Hugs byte-code is lambda-lifted, free variables
1289 become arguments and are expected to be on the stack by the called
1292 Hugs represents updateable thunks with @AP@ objects applying a closure
1293 to a list of arguments. (As for @PAP@s, unboxed arguments should be
1294 preceded by a tag.) When it is entered, it pushes an update frame
1295 followed by its payload on the stack, and enters the first word (which
1296 will be a pointer to a BCO). The layout of @AP@ objects is described
1297 in more detail in Section \ref{sect:AP}.
1299 Partial applications are represented by @PAP@ objects, which are
1302 \ToDo{Hugs Constructors}.
1304 \subsection{Calling conventions}
1305 \label{sect:hugs-calling-conventions}
1306 \label{sect:standard-closures}
1308 The calling convention for any byte-code function is straightforward:
1310 \item Push any arguments on the stack.
1311 \item Push a pointer to the BCO.
1312 \item Begin interpreting the byte code.
1315 In a system containing both GHC and Hugs, the bytecode interpreter
1316 only has to be able to enter BCOs: everything else can be handled by
1317 returning to the compiled world (as described in
1318 Section~\ref{sect:hugs-to-ghc-closure}) and entering the closure
1321 This would work but it would obviously be very inefficient if
1322 we entered a @AP@ by switching worlds, entering the @AP@,
1323 pushing the arguments and function onto the stack, and entering the
1324 function which, likely as not, will be a byte-code object which we
1325 will enter by \emph{returning} to the byte-code interpreter. To avoid
1326 such gratuitious world switching, we choose to recognise certain
1327 closure types as being ``standard'' --- and duplicate the entry code
1328 for the ``standard closures'' in the bytecode interpreter.
1330 A closure is said to be ``standard'' if its entry code is entirely
1331 determined by its info table. \emph{Standard Closures} have the
1332 desirable property that the byte-code interpreter can enter
1333 the closure by simply ``interpreting'' the info table instead of
1334 switching to the compiled world. The standard closures include:
1338 To enter a constructor, we simply return (see Section
1339 \ref{sect:hugs-return-convention}).
1342 To enter an indirection, we simply enter the object it points to
1343 after possibly adjusting the current cost centre.
1347 To enter an @AP@, we push an update frame, push the
1348 arguments, push the function and enter the function.
1349 (Not forgetting a stack check at the start.)
1353 To enter a @PAP@, we push the arguments, push the function and enter
1354 the function. (Not forgetting a stack check at the start.)
1357 To enter a selector, we test whether the selectee is a value. If so,
1358 we simply select the appropriate component; if not, it's simplest to
1359 treat it as a GHC-built closure --- though we could interpret it if we
1364 The most obvious omissions from the above list are @BCO@s (which we
1365 dealt with above) and GHC-built closures (which are covered in Section
1366 \ref{sect:hugs-to-ghc-closure}).
1369 \subsection{Return convention}
1370 \label{sect:hugs-return-convention}
1372 When Hugs pushes a return address, it pushes both a pointer to the BCO
1373 to return to, and a pointer to a static code fragment @HUGS_RET@ (this
1374 will be described in Section \ref{sect:ghc-to-hugs-return}). The
1375 stack layout is shown in Figure \ref{fig:hugs-return-stack}.
1387 %\input{hugs_ret.pstex_t}
1389 \caption{Stack layout for a Hugs return address}
1390 \label{fig:hugs-return-stack}
1401 %\input{hugs_ret2.pstex_t}
1403 \caption{Stack layout on enterings a Hugs return address}
1404 \label{fig:hugs-return2}
1417 %\input{hugs_ret2.pstex_t}
1419 \caption{Stack layout on enterings a Hugs return address with an unboxed value}
1420 \label{fig:hugs-return-int}
1433 %\input{hugs_ret3.pstex_t}
1435 \caption{Stack layout on enterings a GHC return address}
1436 \label{fig:hugs-return3}
1450 | restart |--> id_Int#_closure
1453 %\input{hugs_ret2.pstex_t}
1455 \caption{Stack layout on enterings a GHC return address with an unboxed value}
1456 \label{fig:hugs-return-int}
1459 When a Hugs byte-code sequence enters a closure, it examines the
1460 return address on top of the stack.
1464 \item If the return address is @HUGS_RET@, pop the @HUGS_RET@ and the
1465 bco for the continuation off the stack, push a pointer to the constructor onto
1466 the stack and enter the BCO with the current object pointer set to the BCO
1467 (Figure \ref{fig:hugs-return2}).
1469 \item If the top of the stack is not @HUGS_RET@, we need to do a world
1470 switch as described in Section \ref{sect:hugs-to-ghc-return}.
1475 \part{Implementation}
1479 This part describes the inner workings of the major components of the system.
1480 Their external interfaces are described in the previous part.
1482 The major components of the system are:
1486 \item The storage manager
1487 \item The machine code evaluator (compiled code)
1488 \item The bytecode evaluator (interpreted code)
1493 \section{Hugs Bytecodes}
1494 \label{sect:hugs-bytecodes}
1496 \ToDo{This was in the evaluation model part but it really belongs in
1497 this part which is about the internal details of each of the major
1500 \subsubsection{Addressing Modes}
1502 To avoid potential alignment problems and simplify garbage collection,
1503 all literal constants are stored in two tables (one boxed, the other
1504 unboxed) within each BCO and are referred to by offsets into the tables.
1505 Slots in the constant tables are word aligned.
1507 \ToDo{How big can the offsets be? Is the offset specified in the
1508 address field or in the instruction?}
1510 Literals can have the following types: char, int, nat, float, double,
1511 and pointer to boxed object. There is no real difference between
1512 char, int, nat and float since they all occupy 32 bits --- but it
1513 costs almost nothing to distinguish them and may improve portability
1514 and simplify debugging.
1516 \subsubsection{Compilation}
1519 \def\is{\mbox{\it is}}
1520 \def\ts{\mbox{\it ts}}
1521 \def\as{\mbox{\it as}}
1522 \def\bs{\mbox{\it bs}}
1523 \def\cs{\mbox{\it cs}}
1524 \def\rs{\mbox{\it rs}}
1525 \def\us{\mbox{\it us}}
1526 \def\vs{\mbox{\it vs}}
1527 \def\ws{\mbox{\it ws}}
1528 \def\xs{\mbox{\it xs}}
1530 \def\e{\mbox{\it e}}
1531 \def\alts{\mbox{\it alts}}
1532 \def\fail{\mbox{\it fail}}
1533 \def\panic{\mbox{\it panic}}
1534 \def\ua{\mbox{\it ua}}
1535 \def\obj{\mbox{\it obj}}
1536 \def\bco{\mbox{\it bco}}
1537 \def\tag{\mbox{\it tag}}
1538 \def\entry{\mbox{\it entry}}
1539 \def\su{\mbox{\it su}}
1541 \def\Ind#1{{\mbox{\it Ind}\ {#1}}}
1542 \def\update#1{{\mbox{\it update}\ {#1}}}
1544 \def\next{$\Longrightarrow$}
1545 \def\append{\mathrel{+\mkern-6mu+}}
1546 \def\reverse{\mbox{\it reverse}}
1547 \def\size#1{{\vert {#1} \vert}}
1548 \def\arity#1{{\mbox{\it arity}{#1}}}
1550 \def\AP{\mbox{\it AP}}
1551 \def\PAP{\mbox{\it PAP}}
1552 \def\GHCRET{\mbox{\it GHCRET}}
1553 \def\GHCOBJ{\mbox{\it GHCOBJ}}
1555 To make sense of the instructions, we need a sense of how they will be
1556 used. Here is a small compiler for the STG language.
1559 > cg (f{a1, ... am}) = do
1560 > pushAtom am; ... pushAtom a1
1564 > cg (let{x1=rhs1; ... xm=rhsm in e) = do
1565 > ALLOC x1 |rhs1|, ... ALLOC xm |rhsm|
1566 > build x1 rhs1, ... build xm rhsm
1568 > cg (case e of alts) = do
1569 > PUSHALTS (cgAlts alts)
1572 > cgAlts { alt1; ... altm } = cgAlt alt1 $ ... $ cgAlt altm pmFail
1574 > cgAlt (x@C{xs} -> e) fail = do
1576 > HEAPCHECK (heapUse e)
1580 > build x (C{a1, ... am}) = do
1581 > pushUntaggedAtom am; ... pushUntaggedAtom a1
1583 > build x ({v1, ... vm} \ {}. e) = do
1584 > pushVar vm; ... pushVar v1
1585 > PUSHBCO (cgRhs ({v1, ... vm} \ {}. e))
1587 > build x ({v1, ... vm} \ {x1, ... xm}. e) = do
1588 > pushVar vm; ... pushVar v1
1589 > PUSHBCO (cgRhs ({v1, ... vm} \ {x1, ... xm}. e))
1592 > cgRhs (vs \ xs. e) = do
1593 > ARGCHECK (xs ++ vs) -- can be omitted if xs == {}
1594 > STACKCHECK min(stackUse e,heapOverflowSlop)
1595 > HEAPCHECK (heapUse e)
1598 > pushAtom x = pushVar x
1599 > pushAtom i# = PUSHINT i#
1601 > pushVar x = if isGlobalVar x then PUSHGLOBAL x else PUSHLOCAL x
1603 > pushUntaggedAtom x = pushVar x
1604 > pushUntaggedAtom i# = PUSHUNTAGGEDINT i#
1606 > pushVar x = if isGlobalVar x then PUSHGLOBAL x else PUSHLOCAL x
1609 \ToDo{Is there an easy way to add semi-tagging? Would it be that different?}
1611 \ToDo{Optimise thunks of the form @f{x1,...xm}@ so that we build an AP directly}
1613 \subsubsection{Instructions}
1615 We specify the semantics of instructions using transition rules of
1618 \begin{tabular}{|llrrrrr|}
1620 & $\is$ & $s$ & $\su$ & $h$ & $hp$ & $\sigma$ \\
1621 \next & $\is'$ & $s'$ & $\su'$ & $h'$ & $hp'$ & $\sigma$ \\
1625 where $\is$ is an instruction stream, $s$ is the stack, $\su$ is the
1626 update frame pointer and $h$ is the heap.
1629 \subsubsection{Stack manipulation}
1633 \item[ Push a global variable ].
1635 \begin{tabular}{|llrrrrr|}
1637 & PUSHGLOBAL $o$ : $\is$ & $s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1638 \next & $\is$ & $\sigma!o:s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1642 \item[ Push a local variable ].
1644 \begin{tabular}{|llrrrrr|}
1646 & PUSHLOCAL $o$ : $\is$ & $s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1647 \next & $\is$ & $s!o : s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1651 \item[ Push an unboxed int ].
1653 \begin{tabular}{|llrrrrr|}
1655 & PUSHINT $o$ : $\is$ & $s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1656 \next & $\is$ & $I\# : \sigma!o : s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1660 The $I\#$ is a tag included for the benefit of the garbage collector.
1661 Similar rules exist for floats, doubles, chars, etc.
1663 \item[ Push an unboxed int ].
1665 \begin{tabular}{|llrrrrr|}
1667 & PUSHUNTAGGEDINT $o$ : $\is$ & $s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1668 \next & $\is$ & $\sigma!o : s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1672 Similar rules exist for floats, doubles, chars, etc.
1674 \item[ Delete environment from stack --- ready for tail call ].
1676 \begin{tabular}{|llrrrrr|}
1678 & SLIDE $m$ $n$ : $\is$ & $\as \append \bs \append \cs$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1679 \next & $\is$ & $\as \append \cs$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1683 where $\size{\as} = m$ and $\size{\bs} = n$.
1686 \item[ Push a return address ].
1688 \begin{tabular}{|llrrrrr|}
1690 & PUSHALTS $o$:$\is$ & $s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1691 \next & $\is$ & $@HUGS_RET@:\sigma!o:s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1695 \item[ Push a BCO ].
1697 \begin{tabular}{|llrrrrr|}
1699 & PUSHBCO $o$ : $\is$ & $s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1700 \next & $\is$ & $\sigma!o : s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1706 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1707 \subsubsection{Heap manipulation}
1708 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1712 \item[ Allocate a heap object ].
1714 \begin{tabular}{|llrrrrr|}
1716 & ALLOC $m$ : $\is$ & $s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1717 \next & $\is$ & $hp:s$ & $su$ & $h$ & $hp+m$ & $\sigma$ \\
1721 \item[ Build a constructor ].
1723 \begin{tabular}{|llrrrrr|}
1725 & PACK $o$ $o'$ : $\is$ & $\ws \append s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1726 \next & $\is$ & $s$ & $su$ & $h[s!o \mapsto Pack C\{\ws\}]$ & $hp$ & $\sigma$ \\
1730 where $C = \sigma!o'$ and $\size{\ws} = \arity{C}$.
1732 \item[ Build an AP or PAP ].
1734 \begin{tabular}{|llrrrrr|}
1736 & MKAP $o$ $m$:$\is$ & $f : \ws \append s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1737 \next & $\is$ & $s$ & $su$ & $h[s!o \mapsto \AP(f,\ws)]$ & $hp$ & $\sigma$ \\
1741 where $\size{\ws} = m$.
1743 \begin{tabular}{|llrrrrr|}
1745 & MKPAP $o$ $m$:$\is$ & $f : \ws \append s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1746 \next & $\is$ & $s$ & $su$ & $h[s!o \mapsto \PAP(f,\ws)]$ & $hp$ & $\sigma$ \\
1750 where $\size{\ws} = m$.
1752 \item[ Unpacking a constructor ].
1754 \begin{tabular}{|llrrrrr|}
1756 & UNPACK : $is$ & $a : s$ & $su$ & $h[a \mapsto C\ \ws]$ & $hp$ & $\sigma$ \\
1757 \next & $is'$ & $(\reverse\ \ws) \append a : s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1761 The $\reverse\ \ws$ looks expensive but, since the stack grows down
1762 and the heap grows up, that's actually the cheap way of copying from
1763 heap to stack. Looking at the compilation rules, you'll see that we
1764 always push the args in reverse order.
1769 \subsubsection{Entering a closure}
1773 \item[ Enter a BCO ].
1775 \begin{tabular}{|llrrrrr|}
1777 & [ENTER] & $a : s$ & $su$ & $h[a \mapsto BCO\{\is\} ]$ & $hp$ & $\sigma$ \\
1778 \next & $\is$ & $a : s$ & $su$ & $h$ & $hp$ & $a$ \\
1782 \item[ Enter a PAP closure ].
1784 \begin{tabular}{|llrrrrr|}
1786 & [ENTER] & $a : s$ & $su$ & $h[a \mapsto \PAP(f,\ws)]$ & $hp$ & $\sigma$ \\
1787 \next & [ENTER] & $f : \ws \append s$ & $su$ & $h$ & $hp$ & $???$ \\
1791 \item[ Entering an AP closure ].
1793 \begin{tabular}{|llrrrrr|}
1795 & [ENTER] & $a : s$ & $su$ & $h[a \mapsto \AP(f,ws)]$ & $hp$ & $\sigma$ \\
1796 \next & [ENTER] & $f : \ws \append @UPD_RET@:\su:a:s$ & $su'$ & $h$ & $hp$ & $???$ \\
1802 \item Instead of blindly pushing an update frame for $a$, we can first test whether there's already
1803 an update frame there. If so, overwrite the existing updatee with an indirection to $a$ and
1804 overwrite the updatee field with $a$. (Overwriting $a$ with an indirection to the updatee also
1805 works.) This results in update chains of maximum length 2.
1809 \item[ Returning a constructor ].
1811 \begin{tabular}{|llrrrrr|}
1813 & [ENTER] & $a : @HUGS_RET@ : \alts : s$ & $su$ & $h[a \mapsto C\{\ws\}]$ & $hp$ & $\sigma$ \\
1814 \next & $\alts.\entry$ & $a:s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1819 \item[ Entering an indirection node ].
1821 \begin{tabular}{|llrrrrr|}
1823 & [ENTER] & $a : s$ & $su$ & $h[a \mapsto \Ind{a'}]$ & $hp$ & $\sigma$ \\
1824 \next & [ENTER] & $a' : s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1828 \item[Entering GHC closure].
1830 \begin{tabular}{|llrrrrr|}
1832 & [ENTER] & $a : s$ & $su$ & $h[a \mapsto \GHCOBJ]$ & $hp$ & $\sigma$ \\
1833 \next & [ENTERGHC] & $a : s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1837 \item[Returning a constructor to GHC].
1839 \begin{tabular}{|llrrrrr|}
1841 & [ENTER] & $a : \GHCRET : s$ & $su$ & $h[a \mapsto C \ws]$ & $hp$ & $\sigma$ \\
1842 \next & [ENTERGHC] & $a : \GHCRET : s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1849 \subsubsection{Updates}
1853 \item[ Updating with a constructor].
1855 \begin{tabular}{|llrrrrr|}
1857 & [ENTER] & $a : @UPD_RET@ : ua : s$ & $su$ & $h[a \mapsto C\{\ws\}]$ & $hp$ & $\sigma$ \\
1858 \next & [ENTER] & $a \append s$ & $su$ & $h[au \mapsto \Ind{a}$ & $hp$ & $\sigma$ \\
1862 \item[ Argument checks].
1864 \begin{tabular}{|llrrrrr|}
1866 & ARGCHECK $m$:$\is$ & $a : \as \append s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1867 \next & $\is$ & $a : \as \append s$ & $su$ & $h'$ & $hp$ & $\sigma$ \\
1871 where $m \ge (su - sp)$
1873 \begin{tabular}{|llrrrrr|}
1875 & ARGCHECK $m$:$\is$ & $a : \as \append @UPD_RET@:su:ua:s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1876 \next & $\is$ & $a : \as \append s$ & $su$ & $h'$ & $hp$ & $\sigma$ \\
1880 where $m < (su - sp)$ and
1881 $h' = h[ua \mapsto \Ind{a'}, a' \mapsto \PAP(a,\reverse\ \as) ]$
1883 Again, we reverse the list of values as we transfer them from the
1884 stack to the heap --- reflecting the fact that the stack and heap grow
1885 in different directions.
1889 \subsubsection{Branches}
1893 \item[ Testing a constructor ].
1895 \begin{tabular}{|llrrrrr|}
1897 & TEST $tag$ $is'$ : $is$ & $a : s$ & $su$ & $h[a \mapsto C\ \ws]$ & $hp$ & $\sigma$ \\
1898 \next & $is$ & $a : s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1902 where $C.\tag = tag$
1904 \begin{tabular}{|llrrrrr|}
1906 & TEST $tag$ $is'$ : $is$ & $a : s$ & $su$ & $h[a \mapsto C\ \ws]$ & $hp$ & $\sigma$ \\
1907 \next & $is'$ & $a : s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1911 where $C.\tag \neq tag$
1915 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1916 \subsubsection{Heap and stack checks}
1917 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1919 \begin{tabular}{|llrrrrr|}
1921 & STACKCHECK $stk$:$\is$ & $s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1922 \next & $\is$ & $s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1926 if $s$ has $stk$ free slots.
1928 \begin{tabular}{|llrrrrr|}
1930 & HEAPCHECK $hp$:$\is$ & $s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1931 \next & $\is$ & $s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
1935 if $h$ has $hp$ free slots.
1937 If either check fails, we push the current bco ($\sigma$) onto the
1938 stack and return to the scheduler. When the scheduler has fixed the
1939 problem, it pops the top object off the stack and reenters it.
1944 \item The bytecode CHECK1000 conservatively checks for 1000 words of heap space and 1000 words of stack space.
1945 We use it to reduce code space and instruction decoding time.
1946 \item The bytecode HEAPCHECK1000 conservatively checks for 1000 words of heap space.
1947 It is used in case alternatives.
1951 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1952 \subsubsection{Primops}
1953 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1955 \ToDo{primops take m words and return n words. The expect boxed arguments on the stack.}
1961 \section{Heap objects}
1962 \label{sect:fixed-header}
1964 \ToDo{Fix this picture}
1974 Every {\em heap object} is a contiguous block
1975 of memory, consisting of a fixed-format {\em header} followed
1976 by zero or more {\em data words}.
1978 \ToDo{I absolutely do not believe that every heap object has a header
1979 like this - ADR. I believe that they all have an info pointer but I
1980 see no readon why stack objects and unpointed heap objects would have
1981 an entry count since this will always be zero.}
1983 The header consists of the following fields:
1985 \item A one-word {\em info pointer}, which points to
1986 the object's static {\em info table}.
1987 \item Zero or more {\em admin words} that support
1989 \item Profiling (notably a {\em cost centre} word).
1990 \note{We could possibly omit the cost centre word from some
1991 administrative objects.}
1992 \item Parallelism (e.g. GranSim keeps the object's global address here,
1993 though GUM keeps a separate hash table).
1994 \item Statistics (e.g. a word to track how many times a thunk is entered.).
1996 We add a Ticky word to the fixed-header part of closures. This is
1997 used to indicate if a closure has been updated but not yet entered. It
1998 is set when the closure is updated and cleared when subsequently
2001 NB: It is {\em not} an ``entry count'', it is an
2002 ``entries-after-update count.'' The commoning up of @CONST@,
2003 @CHARLIKE@ and @INTLIKE@ closures is turned off(?) if this is
2004 required. This has only been done for 2s collection.
2009 Most of the RTS is completely insensitive to the number of admin words.
2010 The total size of the fixed header is @FIXED_HS@.
2012 Many heap objects contain fields allowing them to be inserted onto lists
2013 during evaluation or during garbage collection. The lists required by
2014 the evaluator and storage manager are as follows.
2017 \item 2 lists of threads: runnable threads and sleeping threads.
2019 \item The {\em static object list} is a list of all statically
2020 allocated objects which might contain pointers into the heap.
2021 (Section~\ref{sect:static-objects}.)
2023 \item The {\em updated thunk list} is a list of all thunks in the old
2024 generation which have been updated with an indirection.
2025 (Section~\ref{sect:IND_OLDGEN}.)
2027 \item The {\em mutables list} is a list of all other objects in the
2028 old generation which might contain pointers into the new generation.
2029 Most of the object on this list are ``mutable.''
2030 (Section~\ref{sect:mutables}.)
2032 \item The {\em Foreign Object list} is a list of all foreign objects
2033 which have not yet been deallocated. (Section~\ref{sect:FOREIGN}.)
2035 \item The {\em Spark pool} is a doubly(?) linked list of Spark objects
2036 maintained by the parallel system. (Section~\ref{sect:SPARK}.)
2038 \item The {\em Blocked Fetch list} (or
2039 lists?). (Section~\ref{sect:BLOCKED_FETCH}.)
2041 \item For each thread, there is a list of all update frames on the
2042 stack. (Section~\ref{sect:data-updates}.)
2047 \ToDo{The links for these fields are usually inserted immediately
2048 after the fixed header except ...}
2050 \subsection{Info Tables}
2052 An {\em info table} is a contiguous block of memory, {\em laid out
2053 backwards}. That is, the first field in the list that follows
2054 occupies the highest memory address, and the successive fields occupy
2055 successive decreasing memory addresses.
2058 \begin{tabular}{|c|}
2059 \hline Parallelism Info
2060 \\ \hline Profile Info
2061 \\ \hline Debug Info
2062 \\ \hline Tag / Static reference table
2063 \\ \hline Storage manager layout info
2064 \\ \hline Closure type
2065 \\ \hline entry code
2069 An info table has the following contents (working backwards in memory
2072 \item The {\em entry code} for the closure.
2073 This code appears literally as the (large) last entry in the
2074 info table, immediately preceded by the rest of the info table.
2075 An {\em info pointer} always points to the first byte of the entry code.
2077 \item A one-word {\em closure type field}, @INFO_TYPE@, identifies what kind
2078 of closure the object is. The various types of closure are described
2079 in Section~\ref{sect:closures}.
2080 In some configurations, some useful properties of
2081 closures (is it a HNF? can it be sparked?)
2082 are represented as high-order bits so they can be tested quickly.
2084 \item A single pointer or word --- the {\em storage manager info field},
2085 @INFO_SM@, contains auxiliary information describing the closure's
2086 precise layout, for the benefit of the garbage collector and the code
2087 that stuffs graph into packets for transmission over the network.
2089 \item A one-word {\em Tag/Static Reference Table} field, @INFO_SRT@.
2090 For data constructors, this field contains the constructor tag, in the
2091 range $0..n-1$ where $n$ is the number of constructors. For all other
2092 objects it contains a pointer to a table which enables the garbage
2093 collector to identify all accessible code and CAFs. They are fully
2094 described in Section~\ref{sect:srt}.
2096 \item {\em Profiling info\/}
2098 Closure category records are attached to the info table of the
2099 closure. They are declared with the info table. We put pointers to
2100 these ClCat things in info tables. We need these ClCat things because
2101 they are mutable, whereas info tables are immutable. Hashing will map
2102 similar categories to the same hash value allowing statistics to be
2103 grouped by closure category.
2105 Cost Centres and Closure Categories are hashed to provide indexes
2106 against which arbitrary information can be stored. These indexes are
2107 memoised in the appropriate cost centre or category record and
2108 subsequent hashes avoided by the index routine (it simply returns the
2111 There are different features which can be hashed allowing information
2112 to be stored for different groupings. Cost centres have the cost
2113 centre recorded (using the pointer), module and group. Closure
2114 categories have the closure description and the type
2115 description. Records with the same feature will be hashed to the same
2118 The initialisation routines, @init_index_<feature>@, allocate a hash
2119 table in which the cost centre / category records are stored. The
2120 lower bound for the table size is taken from @max_<feature>_no@. They
2121 return the actual table size used (the next power of 2). Unused
2122 locations in the hash table are indicated by a 0 entry. Successive
2123 @init_index_<feature>@ calls just return the actual table size.
2125 Calls to @index_<feature>@ will insert the cost centre / category
2126 record in the @<feature>@ hash table, if not already inserted. The hash
2127 index is memoised in the record and returned.
2129 CURRENTLY ONLY ONE MEMOISATION SLOT IS AVILABLE IN EACH RECORD SO
2130 HASHING CAN ONLY BE DONE ON ONE FEATURE FOR EACH RECORD. This can be
2131 easily relaxed at the expense of extra memoisation space or continued
2134 The initialisation routines must be called before initialisation of
2135 the stacks and heap as they require to allocate storage. It is also
2136 expected that the caller may want to allocate additional storage in
2137 which to store profiling information based on the return table size
2141 \begin{tabular}{|l|}
2145 \\ \hline Description String
2146 \\ \hline Type String
2152 \item[Hash Index] Memoised copy
2154 Is this category selected (-1 == not memoised, selected? 0 or 1)
2156 One of the following values (defined in CostCentre.lh):
2164 A partial application.
2166 A thunk, or suspension.
2171 \item[@ForeignObj_K@]
2172 A Foreign object (non-Haskell heap resident).
2174 The Stable Pointer table. (There should only be one of these but it
2175 represents a form of weak space leak since it can't shrink to meet
2176 non-demand so it may be worth watching separately? ADR)
2177 \item[@INTERNAL_KIND@]
2178 Something internal to the runtime system.
2182 \item[Description] Source derived string detailing closure description.
2183 \item[Type] Source derived string detailing closure type.
2186 \item {\em Parallelism info\/}
2189 \item {\em Debugging info\/}
2195 %-----------------------------------------------------------------------------
2196 \subsection{Kinds of Heap Object}
2197 \label{sect:closures}
2199 Heap objects can be classified in several ways, but one useful one is
2203 {\em Static closures} occupy fixed, statically-allocated memory
2204 locations, with globally known addresses.
2207 {\em Dynamic closures} are individually allocated in the heap.
2210 {\em Stack closures} are closures allocated within a thread's stack
2211 (which is itself a heap object). Unlike other closures, there are
2212 never any pointers to stack closures. Stack closures are discussed in
2213 Section~\ref{sect:stacks}.
2216 A second useful classification is this:
2219 {\em Executive objects}, such as thunks and data constructors,
2220 participate directly in a program's execution. They can be subdivided into
2221 three kinds of objects according to their type:
2224 {\em Pointed objects}, represent values of a {\em pointed} type
2225 (<.pointed types launchbury.>) --i.e.~a type that includes $\bottom$ such as @Int@ or @Int# -> Int#@.
2227 \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#@.
2229 \item {\em Activation frames}, represent ``continuations''. They are
2230 always stored on the stack and are never pointed to by heap objects or
2231 passed as arguments. \note{It's not clear if this will still be true
2232 once we support speculative evaluation.}
2236 \item {\em Administrative objects}, such as stack objects and thread
2237 state objects, do not represent values in the original program.
2240 Only pointed objects can be entered. All pointed objects share a
2241 common header format: the ``pointed header''; while all unpointed
2242 objects share a common header format: the ``unpointed header''.
2243 \ToDo{Describe the difference and update the diagrams to mention
2244 an appropriate header type.}
2246 This section enumerates all the kinds of heap objects in the system.
2247 Each is identified by a distinct @INFO_TYPE@ tag in its info table.
2249 \ToDo{Check this table very carefully}
2251 \begin{tabular}{|l|l|l|l|l|l|l|l|l|l|l|}
2254 closure kind & HNF & UPD & NS & STA & THU & MUT & UPT & BH & IND & Section \\
2260 @CONSTR@ & 1 & & 1 & & & & & & & \ref{sect:CONSTR} \\
2261 @CONSTR_STATIC@ & 1 & & 1 & 1 & & & & & & \ref{sect:CONSTR} \\
2262 @CONSTR_STATIC_NOCAF@ & 1 & & 1 & 1 & & & & & & \ref{sect:CONSTR} \\
2264 @FUN@ & 1 & & ? & & & & & & & \ref{sect:FUN} \\
2265 @FUN_STATIC@ & 1 & & ? & 1 & & & & & & \ref{sect:FUN} \\
2267 @THUNK@ & & 1 & & & 1 & & & & & \ref{sect:THUNK} \\
2268 @THUNK_STATIC@ & & 1 & & 1 & 1 & & & & & \ref{sect:THUNK} \\
2269 @THUNK_SELECTOR@ & & 1 & 1 & & 1 & & & & & \ref{sect:THUNK_SEL} \\
2271 @BCO@ & 1 & & 1 & & & & & & & \ref{sect:BCO} \\
2272 @BCO_CAF@ & & 1 & & & 1 & & & & & \ref{sect:BCO} \\
2274 @AP@ & & 1 & & & 1 & & & & & \ref{sect:AP} \\
2275 @PAP@ & 1 & & 1 & & & & & & & \ref{sect:PAP} \\
2277 @IND@ & ? & & ? & & ? & & & & 1 & \ref{sect:IND} \\
2278 @IND_OLDGEN@ & ? & & ? & & ? & & & & 1 & \ref{sect:IND} \\
2279 @IND_PERM@ & ? & & ? & & ? & & & & 1 & \ref{sect:IND} \\
2280 @IND_OLDGEN_PERM@ & ? & & ? & & ? & & & & 1 & \ref{sect:IND} \\
2281 @IND_STATIC@ & ? & & ? & 1 & ? & & & & 1 & \ref{sect:IND} \\
2288 @ARR_WORDS@ & 1 & & 1 & & & & 1 & & & \ref{sect:ARR_WORDS1},\ref{sect:ARR_WORDS2} \\
2289 @ARR_PTRS@ & 1 & & 1 & & & & 1 & & & \ref{sect:ARR_PTRS} \\
2290 @MUTVAR@ & 1 & & 1 & & & 1 & 1 & & & \ref{sect:MUTVAR} \\
2291 @MUTARR_PTRS@ & 1 & & 1 & & & 1 & 1 & & & \ref{sect:MUTARR_PTRS} \\
2292 @MUTARR_PTRS_FROZEN@ & 1 & & 1 & & & 1 & 1 & & & \ref{sect:MUTARR_PTRS_FROZEN} \\
2294 @FOREIGN@ & 1 & & 1 & & & & 1 & & & \ref{sect:FOREIGN} \\
2296 @BH@ & & 1 & 1 & & ? & ? & & 1 & ? & \ref{sect:BH} \\
2297 @MVAR@ & 1 & & 1 & & & & & & & \ref{sect:MVAR} \\
2298 @IVAR@ & 1 & & 1 & & & & & & & \ref{sect:IVAR} \\
2299 @FETCHME@ & 1 & & 1 & & & & & & & \ref{sect:FETCHME} \\
2303 Activation frames do not live (directly) on the heap --- but they have
2304 a similar organisation. The classification bits are all zero in
2307 \begin{tabular}{|l|l|}\hline
2308 closure kind & Section \\ \hline
2309 @RET_SMALL@ & \ref{sect:activation-records} \\
2310 @RET_VEC_SMALL@ & \ref{sect:activation-records} \\
2311 @RET_BIG@ & \ref{sect:activation-records} \\
2312 @RET_VEC_BIG@ & \ref{sect:activation-records} \\
2313 @UPDATE_FRAME@ & \ref{sect:activation-records} \\
2317 There are also a number of administrative objects. The classification bits are
2318 all zero in administrative objects.
2320 \begin{tabular}{|l|l|}\hline
2321 closure kind & Section \\ \hline
2322 @TSO@ & \ref{sect:TSO} \\
2323 @STACK_OBJECT@ & \ref{sect:STACK_OBJECT} \\
2324 @STABLEPTR_TABLE@ & \ref{sect:STABLEPTR_TABLE} \\
2325 @SPARK_OBJECT@ & \ref{sect:SPARK} \\
2326 @BLOCKED_FETCH@ & \ref{sect:BLOCKED_FETCH} \\
2330 \ToDo{I guess the parallel system has something like a stable ptr
2331 table. Is there any opportunity for sharing code/data structures
2335 \subsection{Classification bits}
2337 The top bits of the @INFO_TYPE@ tag tells what sort of animal the
2340 \begin{tabular}{|l|l|l|} \hline
2341 Abbrev & Bit & Interpretation \\ \hline
2342 HNF & 0 & 1 $\Rightarrow$ Head normal form \\
2343 UPD & 4 & 1 $\Rightarrow$ May be updated (inconsistent with being a HNF) \\
2344 NS & 1 & 1 $\Rightarrow$ Don't spark me (Any HNF will have this set to 1)\\
2345 STA & 2 & 1 $\Rightarrow$ This is a static closure \\
2346 THU & 8 & 1 $\Rightarrow$ Is a thunk \\
2347 MUT & 3 & 1 $\Rightarrow$ Has mutable pointer fields \\
2348 UPT & 5 & 1 $\Rightarrow$ Has an unpointed type (eg a primitive array) \\
2349 BH & 6 & 1 $\Rightarrow$ Is a black hole \\
2350 IND & 7 & 1 $\Rightarrow$ Is an indirection \\
2354 Updatable structures (@_UP@) are thunks that may be shared. Primitive
2355 arrays (@_BM@ -- Big Mothers) are structures that are always held
2356 in-memory (basically extensions of a closure). Because there may be
2357 offsets into these arrays, a primitive array cannot be handled as a
2358 FetchMe in the parallel system, but must be shipped in its entirety if
2359 its parent closure is shipped.
2361 The other bits in the info-type field simply give a unique bit-pattern
2362 to identify the closure type.
2366 #define _NF 0x0001 /* Normal form */
2367 #define _NS 0x0002 /* Don't spark */
2368 #define _ST 0x0004 /* Is static */
2369 #define _MU 0x0008 /* Is mutable */
2370 #define _UP 0x0010 /* Is updatable (but not mutable) */
2371 #define _BM 0x0020 /* Is a "primitive" array */
2372 #define _BH 0x0040 /* Is a black hole */
2373 #define _IN 0x0080 /* Is an indirection */
2374 #define _TH 0x0100 /* Is a thunk */
2379 SPEC_N SPEC | _NF | _NS
2381 SPEC_U SPEC | _UP | _TH
2384 GEN_N GEN | _NF | _NS
2386 GEN_U GEN | _UP | _TH
2389 TUPLE _NF | _NS | _BM
2390 DATA _NF | _NS | _BM
2391 MUTUPLE _NF | _NS | _MU | _BM
2392 IMMUTUPLE _NF | _NS | _BM
2404 CAF _NF | _NS | _ST | _IN
2413 STKO_DYNAMIC STKO | _MU
2414 STKO_STATIC STKO | _ST
2416 SPEC_RBH _NS | _MU | _BH
2417 GEN_RBH _NS | _MU | _BH
2426 An indirection either points to HNF (post update); or is result of
2427 overwriting a FetchMe, in which case the thing fetched is either
2428 under evaluation (BH), or by now an HNF. Thus, indirections get NoSpark flag.
2432 \subsection{Hugs Objects}
2434 \subsubsection{Byte-Code Objects}
2437 A Byte-Code Object (BCO) is a container for a a chunk of byte-code,
2438 which can be executed by Hugs. The byte-code represents a
2439 supercombinator in the program: when hugs compiles a module, it
2440 performs lambda lifting and each resulting supercombinator becomes a
2441 byte-code object in the heap.
2443 There are two kinds of BCO: a standard @BCO@ which has an arity of one
2444 or more, and a @BCO_CAF@ which takes no arguments and can be updated.
2445 When a @BCO_CAF@ is updated, the code is thrown away!
2447 The semantics of BCOs are described in Section
2448 \ref{sect:hugs-heap-objects}. A BCO has the following structure:
2451 \begin{tabular}{|l|l|l|l|l|l|}
2453 \emph{Fixed Header} & \emph{Layout} & \emph{Offset} & \emph{Size} &
2454 \emph{Literals} & \emph{Byte code} \\
2461 \item The entry code is a static code fragment/info table that
2462 returns to the scheduler to invoke Hugs (Section
2463 \ref{sect:ghc-to-hugs-closure}).
2464 \item \emph{Layout} contains the number of pointer literals in the
2465 \emph{Literals} field.
2466 \item \emph{Offset} is the offset to the byte code from the start of
2468 \item \emph{Size} is the number of words of byte code in the object.
2469 \item \emph{Literals} contains any pointer and non-pointer literals used in
2470 the byte-codes (including jump addresses), pointers first.
2471 \item \emph{Byte code} contains \emph{Size} words of non-pointer byte
2475 \subsection{Pointed Objects}
2477 All pointed objects can be entered.
2479 \subsubsection{Function closures}\label{sect:FUN}
2481 Function closures represent lambda abstractions. For example,
2482 consider the top-level declaration:
2484 f = \x -> let g = \y -> x+y
2487 Both @f@ and @g@ are represented by function closures. The closure
2488 for @f@ is {\em static} while that for @g@ is {\em dynamic}.
2490 The layout of a function closure is as follows:
2492 \begin{tabular}{|l|l|l|l|}\hline
2493 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} \\ \hline
2496 The data words (pointers and non-pointers) are the free variables of
2497 the function closure.
2498 The number of pointers
2499 and number of non-pointers are stored in the @INFO_SM@ word, in the least significant
2500 and most significant half-word respectively.
2502 There are several different sorts of function closure, distinguished
2503 by their @INFO_TYPE@ field:
2505 \item @FUN@: a vanilla, dynamically allocated on the heap.
2507 \item $@FUN_@p@_@np$: to speed up garbage collection a number of
2508 specialised forms of @FUN@ are provided, for particular $(p,np)$ pairs,
2509 where $p$ is the number of pointers and $np$ the number of non-pointers.
2511 \item @FUN_STATIC@. Top-level, static, function closures (such as
2512 @f@ above) have a different
2513 layout than dynamic ones:
2515 \begin{tabular}{|l|l|l|}\hline
2516 {\em Fixed header} & {\em Static object link} \\ \hline
2519 Static function closures have no free variables. (However they may refer to other
2520 static closures; these references are recorded in the function closure's SRT.)
2521 They have one field that is not present in dynamic closures, the {\em static object
2522 link} field. This is used by the garbage collector in the same way that to-space
2523 is, to gather closures that have been determined to be live but that have not yet
2525 \note{Static function closures that have no static references, and hence
2526 a null SRT pointer, don't need the static object link field. Is it worth
2527 taking advantage of this? See @CONSTR_STATIC_NOCAF@.}
2530 Each lambda abstraction, $f$, in the STG program has its own private info table.
2531 The following labels are relevant:
2533 \item $f$@_info@ is $f$'s info table.
2534 \item $f$@_entry@ is $f$'s slow entry point (i.e. the entry code of its
2535 info table; so it will label the same byte as $f$@_info@).
2536 \item $f@_fast_@k$ is $f$'s fast entry point. $k$ is the number of arguments
2537 $f$ takes; encoding this number in the fast-entry label occasionally catches some nasty
2538 code-generation errors.
2541 \subsubsection{Data Constructors}\label{sect:CONSTR}
2543 Data-constructor closures represent values constructed with
2544 algebraic data type constructors.
2545 The general layout of data constructors is the same as that for function
2548 \begin{tabular}{|l|l|l|l|}\hline
2549 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} \\ \hline
2553 The SRT pointer in a data constructor's info table is used for the
2554 constructor tag, since a constructor never has any static references.
2556 There are several different sorts of constructor:
2558 \item @CONSTR@: a vanilla, dynamically allocated constructor.
2559 \item @CONSTR_@$p$@_@$np$: just like $@FUN_@p@_@np$.
2560 \item @CONSTR_INTLIKE@.
2561 A dynamically-allocated heap object that looks just like an @Int@. The
2562 garbage collector checks to see if it can common it up with one of a fixed
2563 set of static int-like closures, thus getting it out of the dynamic heap
2566 \item @CONSTR_CHARLIKE@: same deal, but for @Char@.
2568 \item @CONSTR_STATIC@ is similar to @FUN_STATIC@, with the complication that
2569 the layout of the constructor must mimic that of a dynamic constructor,
2570 because a static constructor might be returned to some code that unpacks it.
2571 So its layout is like this:
2573 \begin{tabular}{|l|l|l|l|l|}\hline
2574 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} & {\em Static object link}\\ \hline
2577 The static object link, at the end of the closure, serves the same purpose
2578 as that for @FUN_STATIC@. The pointers in the static constructor can point
2579 only to other static closures.
2581 The static object link occurs last in the closure so that static
2582 constructors can store their data fields in exactly the same place as
2583 dynamic constructors.
2585 \item @CONSTR_STATIC_NOCAF@. A statically allocated data constructor
2586 that guarantees not to point (directly or indirectly) to any CAF
2587 (section~\ref{sect:CAF}). This means it does not need a static object
2588 link field. Since we expect that there might be quite a lot of static
2589 constructors this optimisation makes sense. Furthermore, the @NOCAF@
2590 tag allows the compiler to indicate that no CAFs can be reached
2591 anywhere {\em even indirectly}.
2596 For each data constructor $Con$, two
2597 info tables are generated:
2599 \item $Con$@_info@ labels $Con$'s dynamic info table,
2600 shared by all dynamic instances of the constructor.
2601 \item $Con$@_static@ labels $Con$'s static info table,
2602 shared by all static instances of the constructor.
2605 \subsubsection{Thunks}
2607 \label{sect:THUNK_SEL}
2609 A thunk represents an expression that is not obviously in head normal
2610 form. For example, consider the following top-level definitions:
2612 range = between 1 10
2613 f = \x -> let ys = take x range
2616 Here the right-hand sides of @range@ and @ys@ are both thunks; the former
2617 is static while the latter is dynamic.
2619 The layout of a thunk is the same as that for a function closure,
2620 except that it may have some words of ``slop'' at the end to make sure
2622 at least @MIN_UPD_PAYLOAD@ words in addition to its
2625 \begin{tabular}{|l|l|l|l|l|}\hline
2626 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} & {\em Slop} \\ \hline
2629 The @INFO_SM@ word contains the same information as for function
2630 closures; that is, number of pointers and number of non-pointers (excluding slop).
2632 A thunk differs from a function closure in that it can be updated.
2634 There are several forms of thunk:
2636 \item @THUNK@: a vanilla, dynamically allocated thunk.
2637 The garbage collection code for thunks whose
2638 pointer + non-pointer words is less than @MIN_UPD_PAYLOAD@ differs from
2639 that for function closures and data constructors, because the GC code
2640 has to account for the slop.
2641 \item $@THUNK_@p@_@np$. Similar comments apply.
2642 \item @THUNK_STATIC@. A static thunk is also known as
2643 a {\em constant applicative form}, or {\em CAF}.
2646 \begin{tabular}{|l|l|l|l|l|}\hline
2647 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} & {\em Slop} & {\em Static object link}\\ \hline
2651 \item @THUNK_SELECTOR@ is a (dynamically allocated) thunk
2652 whose entry code performs a simple selection operation from
2653 a data constructor drawn from a single-constructor type. For example,
2656 x = case y of (a,b) -> a
2658 is a selector thunk. A selector thunk is laid out like this:
2660 \begin{tabular}{|l|l|l|l|}\hline
2661 {\em Fixed header} & {\em Selectee pointer} \\ \hline
2664 The @INFO_SM@ word contains the byte offset of the desired word in
2665 the selectee. Note that this is different from all other thunks.
2667 The garbage collector ``peeks'' at the selectee's
2668 tag (in its info table). If it is evaluated, then it goes ahead and do
2669 the selection, and then behaves just as if the selector thunk was an
2670 indirection to the selected field.
2672 evaluated, it treats the selector thunk like any other thunk of that
2673 shape. [Implementation notes.
2674 Copying: only the evacuate routine needs to be special.
2675 Compacting: only the PRStart (marking) routine needs to be special.]
2679 The only label associated with a thunk is its info table:
2681 \item[$f$@_info@] is $f$'s info table.
2685 \subsubsection{Partial applications (PAPs)}\label{sect:PAP}
2687 A partial application (PAP) represents a function applied to too few arguments.
2688 It is only built as a result of updating after an argument-satisfaction
2689 check failure. A PAP has the following shape:
2691 \begin{tabular}{|l|l|l|l|}\hline
2692 {\em Fixed header} & {\em No of arg words} & {\em Function closure} & {\em Arg stack} \\ \hline
2695 The ``arg stack'' is a copy of the chunk of stack above the update
2696 frame; ``no of arg words'' tells how many words it consists of. The
2697 function closure is (a pointer to) the closure for the function whose
2698 argument-satisfaction check failed.
2700 There is just one standard form of PAP with @INFO_TYPE@ = @PAP@.
2701 There is just one info table too, called @PAP_info@.
2702 Its entry code simply copies the arg stack chunk back on top of the
2703 stack and enters the function closure. (It has to do a stack overflow test first.)
2705 PAPs are also used to implement Hugs functions (where the arguments are free variables).
2706 PAPs generated by Hugs can be static.
2708 \subsubsection{@AP@ objects}
2711 @AP@ objects are used to represent thunks built by Hugs. The only distintion between
2712 an @AP@ and a @PAP@ is that an @AP@ is updateable.
2715 \begin{tabular}{|l|l|l|l|}
2717 \emph{Fixed Header} & {\em No of arg words} & {\em Function closure} & {\em Arg stack} \\
2722 The entry code pushes an update frame, copies the arg stack chunk on
2723 top of the stack, and enters the function closure. (It has to do a
2724 stack overflow test first.)
2726 The ``arg stack'' is a block of (tagged) arguments representing the
2727 free variables of the thunk; ``no of arg words'' tells how many words
2728 it consists of. The function closure is (a pointer to) the closure
2729 for the thunk. The argument stack may be empty if the thunk has no
2733 \subsubsection{Indirections}
2735 \label{sect:IND_OLDGEN}
2737 Indirection closures just point to other closures. They are introduced
2738 when a thunk is updated to point to its value.
2739 The entry code for all indirections simply enters the closure it points to.
2741 There are several forms of indirection:
2743 \item[@IND@] is the vanilla, dynamically-allocated indirection.
2744 It is removed by the garbage collector. It has the following
2747 \begin{tabular}{|l|l|l|}\hline
2748 {\em Fixed header} & {\em Target closure} \\ \hline
2752 \item[@IND_OLDGEN@] is the indirection used to update an old-generation
2753 thunk. Its shape is like this:
2755 \begin{tabular}{|l|l|l|}\hline
2756 {\em Fixed header} & {\em Mutable link field} & {\em Target closure} \\ \hline
2759 It contains a {\em mutable link field} that is used to string together
2760 all old-generation indirections that might have a pointer into
2764 \item[@IND_PERMANENT@ and @IND_OLDGEN_PERMANENT@.]
2765 for lexical profiling, it is necessary to maintain cost centre
2766 information in an indirection, so ``permanent indirections'' are
2767 retained forever. Otherwise they are just like vanilla indirections.
2768 \note{If a permanent indirection points to another permanent
2769 indirection or a @CONST@ closure, it is possible to elide the indirection
2770 since it will have no effect on the profiler.}
2771 \note{Do we still need @IND@ and @IND_OLDGEN@
2772 in the profiling build, or can we just make
2773 do with one pair whose behaviour changes when profiling is built?}
2775 \item[@IND_STATIC@] is used for overwriting CAFs when they have been
2776 evaluated. Static indirections are not removed by the garbage
2777 collector; and are statically allocated outside the heap (and should
2778 stay there). Their static object link field is used just as for
2779 @FUN_STATIC@ closures.
2782 \begin{tabular}{|l|l|l|}
2784 {\em Fixed header} & {\em Target closure} & {\em Static object link} \\
2791 \subsubsection{Activation Records}
2793 Activation records are parts of the stack described by return address
2794 info tables (closures with @INFO_TYPE@ values of @RET_SMALL@,
2795 @RET_VEC_SMALL@, @RET_BIG@ and @RET_VEC_BIG@). They are described in
2796 section~\ref{sect:activation-records}.
2799 \subsubsection{Black holes, MVars and IVars}
2804 Black hole closures are used to overwrite closures currently being
2805 evaluated. They inform the garbage collector that there are no live
2806 roots in the closure, thus removing a potential space leak.
2808 Black holes also become synchronization points in the threaded world.
2809 They contain a pointer to a list of blocked threads to be awakened
2810 when the black hole is updated (or @NULL@ if the list is empty).
2812 \begin{tabular}{|l|l|l|}
2814 {\em Fixed header} & {\em Mutable link} & {\em Blocked thread link} \\
2818 The {\em Blocked thread link} points to the TSO of the first thread
2819 waiting for the value of this thunk. All subsequent TSOs in the list
2820 are linked together using their @TSO_LINK@ field.
2822 When the blocking queue is non-@NULL@, the black hole must be added to
2823 the mutables list since the TSOs on the list may contain pointers into
2824 the new generation. There is no need to clutter up the mutables list
2825 with black holes with empty blocking queues.
2830 \subsubsection{FetchMes}\label{sect:FETCHME}
2832 In the parallel systems, FetchMes are used to represent pointers into
2833 the global heap. When evaluated, the value they point to is read from
2836 \ToDo{Describe layout}
2839 \subsection{Unpointed Objects}
2841 A variable of unpointed type is always bound to a {\em value}, never to a {\em thunk}.
2842 For this reason, unpointed objects cannot be entered.
2844 A {\em value} may be:
2846 \item {\em Boxed}, i.e.~represented indirectly by a pointer to a heap object (e.g.~foreign objects, arrays); or
2847 \item {\em Unboxed}, i.e.~represented directly by a bit-pattern in one or more registers (e.g.~@Int#@ and @Float#@).
2849 All {\em pointed} values are {\em boxed}.
2851 \subsubsection{Immutable Objects}
2852 \label{sect:ARR_WORDS1}
2853 \label{sect:ARR_PTRS}
2856 \item[@ARR_WORDS@] is a variable-sized object consisting solely of
2857 non-pointers. It is used for arrays of all
2858 sorts of things (bytes, words, floats, doubles... it doesn't matter).
2860 \begin{tabular}{|c|c|c|c|}
2862 {\em Fixed Hdr} & {\em No of non-pointers} & {\em Non-pointers\ldots} \\ \hline
2866 \item[@ARR_PTRS@] is an immutable, variable sized array of pointers.
2868 \begin{tabular}{|c|c|c|c|}
2870 {\em Fixed Hdr} & {\em Mutable link} & {\em No of pointers} & {\em Pointers\ldots} \\ \hline
2873 The mutable link is present so that we can easily freeze and thaw an
2874 array (by changing the header and adding/removing the array to the
2879 \subsubsection{Mutable Objects}
2880 \label{sect:mutables}
2881 \label{sect:ARR_WORDS2}
2883 \label{sect:MUTARR_PTRS}
2884 \label{sect:MUTARR_PTRS_FROZEN}
2886 Some of these objects are {\em mutable}; they represent objects which
2887 are explicitly mutated by Haskell code through the @ST@ monad.
2888 They're not used for thunks which are updated precisely once.
2889 Depending on the garbage collector, mutable closures may contain extra
2890 header information which allows a generational collector to implement
2891 the ``write barrier.''
2895 \item[@ARR_WORDS@] is also used to represent {\em mutable} arrays of
2896 bytes, words, floats, doubles, etc. It's possible to use the same
2897 object type because even generational collectors don't need to
2900 \item[@MUTVAR@] is a mutable variable.
2902 \begin{tabular}{|c|c|c|}
2904 {\em Fixed Hdr} & {\em Mutable link} & {\em Pointer} \\ \hline
2908 \item[@MUTARR_PTRS@] is a mutable array of pointers.
2909 Such an array may be {\em frozen}, becoming an @SM_MUTARR_PTRS_FROZEN@, with a
2910 different info-table.
2912 \begin{tabular}{|c|c|c|c|}
2914 {\em Fixed Hdr} & {\em Mutable link} & {\em No of ptrs} & {\em Pointers\ldots} \\ \hline
2918 \item[@MUTARR_PTRS_FROZEN@] is a frozen @MUTARR_PTRS@ closure.
2919 The garbage collector converts @MUTARR_PTRS_FROZEN@ to @ARR_PTRS@ as it removes them from
2925 \subsubsection{Foreign Objects}\label{sect:FOREIGN}
2927 Here's what a ForeignObj looks like:
2930 \begin{tabular}{|l|l|l|l|}
2932 {\em Fixed header} & {\em Data} & {\em Free Routine} & {\em Foreign object link} \\
2937 The @FreeRoutine@ is a reference to the finalisation routine to call
2938 when the @ForeignObj@ becomes garbage. If @freeForeignObject@ is
2939 called on a Foreign Object, the @FreeRoutine@ is set to zero and the
2940 garbage collector will not attempt to call @FreeRoutine@ when the
2941 object becomes garbage.
2943 The Foreign object link is a link to the next foreign object in the
2944 list. This list is traversed at the end of garbage collection: if an
2945 object is about to be deallocated (e.g.~it was not marked or
2946 evacuated), the free routine is called and the object is deleted from
2950 The remaining objects types are all administrative --- none of them may be entered.
2952 \subsection{Thread State Objects (TSOs)}\label{sect:TSO}
2954 In the multi-threaded system, the state of a suspended thread is
2955 packed up into a Thread State Object (TSO) which contains all the
2956 information needed to restart the thread and for the garbage collector
2957 to find all reachable objects. When a thread is running, it may be
2958 ``unpacked'' into machine registers and various other memory locations
2959 to provide faster access.
2961 Single-threaded systems don't really {\em need\/} TSOs --- but they do
2962 need some way to tell the storage manager about live roots so it is
2963 convenient to use a single TSO to store the mutator state even in
2964 single-threaded systems.
2966 Rather than manage TSOs' alloc/dealloc, etc., in some {\em ad hoc}
2967 way, we instead alloc/dealloc/etc them in the heap; then we can use
2968 all the standard garbage-collection/fetching/flushing/etc machinery on
2969 them. So that's why TSOs are ``heap objects,'' albeit very special
2972 \begin{tabular}{|l|l|}
2973 \hline {\em Fixed header}
2974 \\ \hline @TSO_LINK@
2975 \\ \hline @TSO_WHATNEXT@
2976 \\ \hline @TSO_WHATNEXT_INFO@
2977 \\ \hline @TSO_STACK@
2978 \\ \hline {\em Exception Handlers}
2979 \\ \hline {\em Ticky Info}
2980 \\ \hline {\em Profiling Info}
2981 \\ \hline {\em Parallel Info}
2982 \\ \hline {\em GranSim Info}
2986 The contents of a TSO are:
2989 \item A pointer (@TSO_LINK@) used to maintain a list of threads with a similar
2990 state (e.g.~all runnable, all sleeping, all blocked on the same black
2991 hole, all blocked on the same MVar, etc.)
2993 \item A word (@TSO_WHATNEXT@) which is in suspended threads to record
2994 how to awaken it. This typically requires a program counter which is stored
2995 in the pointer @TSO_WHATNEXT_INFO@
2997 \item A pointer (@TSO_STACK@) to the top stack block.
2999 \item Optional information for ``Ticky Ticky'' statistics: @TSO_STK_HWM@ is
3000 the maximum number of words allocated to this thread.
3002 \item Optional information for profiling:
3003 @TSO_CCC@ is the current cost centre.
3005 \item Optional information for parallel execution:
3008 \item The types of threads (@TSO_TYPE@):
3010 \item[@T_MAIN@] Must be executed locally.
3011 \item[@T_REQUIRED@] A required thread -- may be exported.
3012 \item[@T_ADVISORY@] An advisory thread -- may be exported.
3013 \item[@T_FAIL@] A failure thread -- may be exported.
3016 \item I've no idea what else
3020 \item Optional information for GranSim execution:
3037 \item clock (gransim light only)
3041 Here are the various queues for GrAnSim-type events.
3052 \subsection{Other weird objects}
3054 \label{sect:BLOCKED_FETCH}
3057 \item[@BlockedFetch@ heap objects (`closures')] (parallel only)
3059 @BlockedFetch@s are inbound fetch messages blocked on local closures.
3060 They arise as entries in a local blocking queue when a fetch has been
3061 received for a local black hole. When awakened, we look at their
3062 contents to figure out where to send a resume.
3064 A @BlockedFetch@ closure has the form:
3066 \begin{tabular}{|l|l|l|l|l|l|}\hline
3067 {\em Fixed header} & link & node & gtid & slot & weight \\ \hline
3071 \item[Spark Closures] (parallel only)
3073 Spark closures are used to link together all closures in the spark pool. When
3074 the current processor is idle, it may choose to speculatively evaluate some of
3075 the closures in the pool. It may also choose to delete sparks from the pool.
3077 \begin{tabular}{|l|l|l|l|l|l|}\hline
3078 {\em Fixed header} & {\em Spark pool link} & {\em Sparked closure} \\ \hline
3086 \subsection{Stack Objects}
3087 \label{sect:STACK_OBJECT}
3090 These are ``stack objects,'' which are used in the threaded world as
3091 the stack for each thread is allocated from the heap in smallish
3092 chunks. (The stack in the sequential world is allocated outside of
3095 Each reduction thread has to have its own stack space. As there may
3096 be many such threads, and as any given one may need quite a big stack,
3097 a naive give-'em-a-big-stack-and-let-'em-run approach will cost a {\em
3100 Our approach is to give a thread a small stack space, and then link
3101 on/off extra ``chunks'' as the need arises. Again, this is a
3102 storage-management problem, and, yet again, we choose to graft the
3103 whole business onto the existing heap-management machinery. So stack
3104 objects will live in the heap, be garbage collected, etc., etc..
3106 A stack object is laid out like this:
3109 \begin{tabular}{|l|}
3113 {\em Link to next stack object (0 for last)}
3115 {\em N, the payload size in words}
3117 {\em @Sp@ (byte offset from head of object)}
3119 {\em @Su@ (byte offset from head of object)}
3121 {\em Payload (N words)}
3126 \ToDo{Are stack objects on the mutable list?}
3128 The stack grows downwards, towards decreasing
3129 addresses. This makes it easier to print out the stack
3130 when debugging, and it means that a return address is
3131 at the lowest address of the chunk of stack it ``knows about''
3132 just like an info pointer on a closure.
3134 The garbage collector needs to be able to find all the
3135 pointers in a stack. How does it do this?
3139 \item Within the stack there are return addresses, pushed
3140 by @case@ expressions. Below a return address (i.e. at higher
3141 memory addresses, since the stack grows downwards) is a chunk
3142 of stack that the return address ``knows about'', namely the
3143 activation record of the currently running function.
3145 \item Below each such activation record is a {\em pending-argument
3146 section}, a chunk of
3147 zero or more words that are the arguments to which the result
3148 of the function should be applied. The return address does not
3150 ``know'' how many pending arguments there are, or their types.
3151 (For example, the function might return a result of type $\alpha$.)
3153 \item Below each pending-argument section is another return address,
3154 and so on. Actually, there might be an update frame instead, but we
3155 can consider update frames as a special case of a return address with
3156 a well-defined activation record.
3158 \ToDo{Doesn't it {\em have} to be an update frame? After all, the arg
3159 satisfaction check is @Su - Sp >= ...@.}
3163 The game plan is this. The garbage collector
3164 walks the stack from the top, traversing pending-argument sections and
3165 activation records alternately. Next we discuss how it finds
3166 the pointers in each of these two stack regions.
3169 \subsubsection{Activation records}\label{sect:activation-records}
3171 An {\em activation record} is a contiguous chunk of stack,
3172 with a return address as its first word, followed by as many
3173 data words as the return address ``knows about''. The return
3174 address is actually a fully-fledged info pointer. It points
3175 to an info table, replete with:
3178 \item entry code (i.e. the code to return to).
3179 \item @INFO_TYPE@ is either @RET_SMALL/RET_VEC_SMALL@ or @RET_BIG/RET_VEC_BIG@, depending
3180 on whether the activation record has more than 32 data words (\note{64 for 8-byte-word architectures}) and on whether
3181 to use a direct or a vectored return.
3182 \item @INFO_SM@ for @RET_SMALL@ is a bitmap telling the layout
3183 of the activation record, one bit per word. The least-significant bit
3184 describes the first data word of the record (adjacent to the fixed
3185 header) and so on. A ``@1@'' indicates a non-pointer, a ``@0@''
3187 a pointer. We don't need to indicate exactly how many words there
3189 because when we get to all zeros we can treat the rest of the
3190 activation record as part of the next pending-argument region.
3192 For @RET_BIG@ the @INFO_SM@ field points to a block of bitmap
3193 words, starting with a word that tells how many words are in
3196 \item @INFO_SRT@ is the Static Reference Table for the return
3197 address (Section~\ref{sect:srt}).
3200 The activation record is a fully fledged closure too.
3201 As well as an info pointer, it has all the other attributes of
3202 a fixed header (Section~\ref{sect:fixed-header}) including a saved cost
3203 centre which is reloaded when the return address is entered.
3205 In other words, all the attributes of closures are needed for
3206 activation records, so it's very convenient to make them look alike.
3209 \subsubsection{Pending arguments}
3211 So that the garbage collector can correctly identify pointers
3212 in pending-argument sections we explicitly tag all non-pointers.
3213 Every non-pointer in a pending-argument section is preceded
3214 (at the next lower memory word) by a one-word byte count that
3215 says how many bytes to skip over (excluding the tag word).
3217 The garbage collector traverses a pending argument section from
3218 the top (i.e. lowest memory address). It looks at each word in turn:
3221 \item If it is less than or equal to a small constant @MAX_STACK_TAG@
3223 it treats it as a tag heralding zero or more words of non-pointers,
3224 so it just skips over them.
3226 \item If it points to the code segment, it must be a return
3227 address, so we have come to the end of the pending-argument section.
3229 \item Otherwise it must be a bona fide heap pointer.
3233 \subsection{The Stable Pointer Table}\label{sect:STABLEPTR_TABLE}
3235 A stable pointer is a name for a Haskell object which can be passed to
3236 the external world. It is ``stable'' in the sense that the name does
3237 not change when the Haskell garbage collector runs---in contrast to
3238 the address of the object which may well change.
3240 A stable pointer is represented by an index into the
3241 @StablePointerTable@. The Haskell garbage collector treats the
3242 @StablePointerTable@ as a source of roots for GC.
3244 In order to provide efficient access to stable pointers and to be able
3245 to cope with any number of stable pointers (eg $0 \ldots 100000$), the
3246 table of stable pointers is an array stored on the heap and can grow
3247 when it overflows. (Since we cannot compact the table by moving
3248 stable pointers about, it seems unlikely that a half-empty table can
3249 be reduced in size---this could be fixed if necessary by using a
3250 hash table of some sort.)
3252 In general a stable pointer table closure looks like this:
3255 \begin{tabular}{|l|l|l|l|l|l|l|l|l|l|l|}
3257 {\em Fixed header} & {\em No of pointers} & {\em Free} & $SP_0$ & \ldots & $SP_{n-1}$
3265 \item[@NPtrs@:] number of (stable) pointers.
3267 \item[@Free@:] the byte offset (from the first byte of the object) of the first free stable pointer.
3269 \item[$SP_i$:] A stable pointer slot. If this entry is in use, it is
3270 an ``unstable'' pointer to a closure. If this entry is not in use, it
3271 is a byte offset of the next free stable pointer slot.
3275 When a stable pointer table is evacuated
3277 \item the free list entries are all set to @NULL@ so that the evacuation
3278 code knows they're not pointers;
3280 \item The stable pointer slots are scanned linearly: non-@NULL@ slots
3281 are evacuated and @NULL@-values are chained together to form a new free list.
3284 There's no need to link the stable pointer table onto the mutable
3285 list because we always treat it as a root.
3289 \section{The Storage Manager}
3291 The generational collector remembers the depth of the last generation
3292 collected and the value of the heap pointer at the end of the last GC.
3293 If the mutator has not moved the heap pointer, that means that the
3294 amount of space recovered is insufficient to satisfy even one request
3295 and it is time to collect an older generation or report a heap overflow.
3297 A deeper collection is also triggered when a minor collection fails to
3298 recover at least @...@ bytes of space.
3300 When can a GC happen?
3303 - During updates (ie during returns)
3304 - When a heap check fails
3305 - When a stack check fails (concurrent system only)
3306 - When a context switch happens (concurrent system only)
3308 When do heap checks occur?
3309 - Immediately after entering a thunk
3310 - Immediately after entering a case alternative
3312 When do stack checks occur?
3313 - We calculate the worst-case stack usage of an entire
3314 thunk so there's no need to put a check inside each alternative.
3315 - Immediately after entering a thunk
3316 We can't make a similar worst-case calculation for heap usage
3317 because the heap isn't used in a stacklike manner so any
3318 evaluation inside a case might steal some of the heap we've
3322 - Threads can be blocked
3323 - Threads can be put to sleep
3324 - Heap may move while we sleep
3325 - Black holing may happen while we sleep (ie during GC)
3328 \subsection{The SM state}
3330 Contains @Hp@, @HpLim@, @StablePtrTable@ plus version-specific info.
3334 \item Static Object list
3335 \item Foreign Object list
3336 \item Stable Pointer Table
3340 In addition, the generational collector requires:
3344 \item Old Generation Indirection list
3345 \item Mutables list --- list of mutable objects in the old generation.
3346 \item @OldLim@ --- the boundary between the generations
3347 \item Old Foreign Object list --- foreign objects in the old generation
3351 It is passed a table of {\em roots\/} containing
3355 \item All runnable TSOs
3360 In the parallel system, there must be some extra magic associated with
3363 \subsection{The SM interface}
3365 @initSM@ finalizes any runtime parameters of the storage manager.
3367 @exitSM@ does any cleaning up required by the storage manager before
3368 the program is executed. Its main purpose is to print any summary
3371 @initHeap@ allocates the heap. It initialises the @hp@ and @hplim@
3372 fields of @sm@ to represent an empty heap for the compiled-in garbage
3373 collector. It also initialises @CAFlist@ to be the empty list. If we
3374 are using Appel's collector it also initialises the @OldLim@ field.
3375 It also initialises the stable pointer table and the @ForeignObjList@
3376 (and @OldForeignObjList@) fields.
3378 @collectHeap@ invokes the garbage collector. @collectHeap@ requires
3379 all the fields of @sm@ to be initialised appropriately (from the
3380 STG-machine registers). The following are identified as heap roots:
3382 \item The updated CAFs recorded in @CAFlist@.
3383 \item Any pointers found on the stack.
3384 \item All runnable and sleeping TSOs.
3385 \item The stable pointer table.
3388 There are two possible results from a garbage collection:
3391 The garbage collector is unable to free up any more space.
3394 The garbage collector managed to free up more space.
3397 \item @hp@ and @hplim@ will indicate the new space available for
3400 \item The elements of @CAFlist@ and the stable pointers will be
3401 updated to point to the new locations of the closures they reference.
3403 \item Any members of @ForeignObjList@ which became garbage should have
3404 been reported (by calling their finalising routines; and the
3405 @(Old)ForeignObjList@ updated to contain only those Foreign objects
3406 which are still live.
3413 %************************************************************************
3415 \subsection{``What really happens in a garbage collection?''}
3417 %************************************************************************
3419 This is a brief tutorial on ``what really happens'' going to/from the
3420 storage manager in a garbage collection.
3423 %------------------------------------------------------------------------
3424 \item[The heap check:]
3428 If you gaze into the C output of GHC, you see many macros calls like:
3430 HEAP_CHK_2PtrsLive((_FHS+2));
3433 This expands into the C (roughly speaking...):
3435 Hp = Hp + (_FHS+2); /* optimistically move heap pointer forward */
3437 GC_WHILE_OR_IF (HEAP_OVERFLOW_OP(Hp, HpLim) OR_INTERVAL_EXPIRED) {
3438 STGCALL2_GC(PerformGC, <liveness-bits>, (_FHS+2));
3442 In the parallel world, where we will need to re-try the heap check,
3443 @GC_WHILE_OR_IF@ will be a ``while''; in the sequential world, it will
3446 The ``heap lookahead'' checks, which are similar and used for
3447 multi-precision @Integer@ ops, have some further complications. See
3448 the commentary there (@StgMacros.lh@).
3450 %------------------------------------------------------------------------
3451 \item[Into @callWrapper_GC@...:]
3453 When we failed the heap check (above), we were inside the
3454 GCC-registerised ``threaded world.'' @callWrapper_GC@ is all about
3455 getting in and out of the threaded world. On SPARCs, with register
3456 windows, the name of the game is not shifting windows until we have
3457 what we want out of the old one. In tricky cases like this, it's best
3458 written in assembly language.
3460 Performing a GC (potentially) means giving up the thread of control.
3461 So we must fill in the thread-state-object (TSO) [and its associated
3462 stk object] with enough information for later resumption:
3465 Save the return address in the TSO's PC field.
3467 Save the machine registers used in the STG threaded world in their
3468 corresponding TSO fields. We also save the pointer-liveness
3469 information in the TSO.
3471 The registers that are not thread-specific, notably @Hp@ and
3472 @HpLim@, are saved in the @StorageMgrInfo@ structure.
3474 Call the routine it was asked to call; in this example, call
3475 @PerformGC@ with arguments @<liveness>@ and @_FHS+2@ (some constant)...
3479 %------------------------------------------------------------------------
3480 \item[Into the heap overflow wrapper, @PerformGC@ [parallel]:]
3482 Most information has already been saved in the TSO.
3486 The first argument (@<liveness>@, in our example) say what registers
3487 are live, i.e., are ``roots'' the storage manager needs to know.
3489 StorageMgrInfo.rootno = 2;
3490 StorageMgrInfo.roots[0] = (P_) Ret1_SAVE;
3491 StorageMgrInfo.roots[1] = (P_) Ret2_SAVE;
3495 We move the heap-pointer back [we had optimistically
3496 advanced it, in the initial heap check]
3499 We load up the @smInfo@ data from the STG registers' @*_SAVE@ locations.
3502 We mark on the scheduler's big ``blackboard'' that a GC is
3506 We reschedule, i.e., this thread gives up control. (The scheduler
3507 will presumably initiate a garbage-collection, but it may have to do
3508 any number of other things---flushing, for example---before ``normal
3509 execution'' resumes; and it most certainly may not be this thread that
3510 resumes at that point!)
3513 IT IS AT THIS POINT THAT THE WORLD IS COMPLETELY TIDY.
3515 %------------------------------------------------------------------------
3516 \item[Out of @callWrapper_GC@ [parallel]:]
3518 When this thread is finally resumed after GC (and who knows what
3519 else), it will restart by the normal enter-TSO/enter-stack-object
3520 sequence, which has the effect of re-loading the registers, etc.,
3521 (i.e., restoring the state).
3523 Because the address we saved in the TSO's PC field was that at the end
3524 of the heap check, and because the check is a while-loop in the
3525 parallel system, we will now loop back around, and make sure there is
3526 enough space before continuing.
3531 \subsection{Static Reference Tables (SRTs)}
3534 \label{sect:static-objects}
3536 In the above, we assumed that objects always contained pointers to all
3537 their free variables. In fact, this isn't quite true: GHC omits
3538 pointers to top-level objects and allocates their closures in static
3539 memory. This optimisation reduces the number of free variables in
3540 heap objects - reducing memory usage and the effort needed to put them
3541 into heap objects. However, this optimisation comes at a cost: we
3542 need to complicate the garbage collector with machinery for tracing
3543 these static references.
3545 Early versions of GHC used a very simple algorithm: it treated all
3546 static objects as roots. This is safe in the sense that no object is
3547 ever deallocated if there's a chance that it might be required later
3548 but can lead to some terrible space leaks. For example, this program
3549 ought to be able to run in constant space but, because @xs@ is never
3550 deallocated, it runs in linear space.
3557 The correct behaviour is for the garbage collector to keep a static
3558 object alive iff it might be required later in execution. That is, if
3559 it is reachable from any live heap objects {\em or\/} from any return
3560 addresses found on the stack or from the current program counter.
3561 Since it is obviously infeasible for the garbage collector to scan
3562 machine code looking for static references, the code generator must
3563 generate a table of all static references in any piece of code (and we
3564 must place a pointer to this table next to any piece of code we
3567 Here's what the SRT has to contain:
3573 Here's how we represent it:
3577 must be able to handle 0 references well
3584 o Generational GC trickery
3587 \subsection{Space leaks and black holes}
3588 \label{sect:black-hole}
3592 \ToDo{Insert text stolen from update paper}
3596 A program exhibits a {\em space leak} if it retains storage that is
3597 sure not to be used again. Space leaks are becoming increasingly
3598 common in imperative programs that @malloc@ storage and fail
3599 subsequently to @free@ it. They are, however, also common in
3600 garbage-collected systems, especially where lazy evaluation is
3601 used.[.wadler leak, runciman heap profiling jfp.]
3603 Quite a bit of experience has now accumulated suggesting that
3604 implementors must be very conscientious about avoiding gratuitous
3605 space leaks --- that is, ones which are an accidental artefact of some
3606 implementation technique.[.appel book.] The update mechanism is
3607 a case in point, as <.jones jfp leak.> points out. Consider a thunk for
3610 let xs = [1..1000] in last xs
3612 where @last@ is a function that returns the last element of its
3613 argument list. When the thunk is entered it will call @last@, which
3614 will consume @xs@ until it finds the last element. Since the list
3615 @[1..1000]@ is produced lazily one might reasonably expect the
3616 expression to evaluate in constant space. But {\em until the moment
3617 of update, the thunk itself still retains a pointer to the beginning
3618 of the list @xs@}. So, until the update takes place the whole list
3621 Of course, this is completely gratuitous. The pointer to @xs@ in the
3622 thunk will never be used again. In <.peyton stock hardware.> the solution to
3623 this problem that we advocated was to overwrite a thunk's info with a
3624 fixed ``black hole'' info pointer, {\em at the moment of entry}. The
3625 storage management information attached to a black-hole info pointer
3626 tells the garbage collector that the closure contains no pointers,
3627 thereby plugging the space leak.
3629 \subsubsection{Lazy black-holing}
3630 \label{sect:lazy-black-holing}
3632 \Note{We currently plan to implement eager black holing because the
3633 lazy blackholing scheme leavs "slop" in the heap.}
3635 Black-holing is a well-known idea. The trouble is that it is
3636 gallingly expensive. To avoid the occasional space leak, for every
3637 single thunk entry we have to load a full-word literal constant into a
3638 register (often two instructions) and then store that register into a
3641 Fortunately, this cost can easily be avoided. The
3642 idea is simple: {\em instead of black-holing every thunk on entry,
3643 wait until the garbage collector is called, and then black-hole all
3644 (and only) the thunks whose evaluation is in progress at that moment}.
3645 There is no benefit in black-holing a thunk that is updated before
3646 garbage collection strikes! In effect, the idea is to perform the
3647 black-holing operation lazily, only when it is needed. This
3648 dramatically cuts down the number of black-holing operations, as our
3649 results show {\em forward ref}.
3651 How can we find all the thunks whose evaluation is in progress? They
3652 are precisely the ones for which update frames are on the stack. So
3653 all we need do is find all the update frames (via the @Su@ chain) and
3654 black-hole their thunks right at the start of garbage collection.
3655 Notice that it is not enough to refrain from treating update frames as
3656 roots: firstly because the thunks to which they point may need to be
3657 moved in a copying collector, but more importantly because the thunk
3658 might be accessible via some other route.
3660 \subsubsection{Detecting loops}
3662 Black-holing has a second minor advantage: evaluation of a thunk whose
3663 value depends on itself will cause a black hole closure to be entered,
3664 which can cause a suitable error message to be displayed. For example,
3665 consider the definition
3669 The code to evaluate @x@'s right hand side will evaluate @x@. In the
3670 absence of black-holing, the result will be a stack overflow, as the
3671 evaluator repeatedly pushes a return address and enters @x@. If
3672 thunks are black-holed on entry, then this infinite loop can be caught
3675 With our new method of lazy black-holing, a self-referential program
3676 might cause either stack overflow or a black-hole error message,
3677 depending on exactly when garbage collection strikes. It is quite
3678 easy to conceal these differences, however. If stack overflow occurs,
3679 all we need do is examine the update frames on the stack to see if
3680 more than one refers to the same thunk. If so, there is a loop that
3681 would have been detected by eager black-holing.
3683 \subsubsection{Lazy locking}
3686 In a parallel implementation, it is necessary somehow to ``lock'' a
3687 thunk that is under evaluation, so that other parallel evaluators
3688 cannot simultaneously evaluate it and thereby duplicate work.
3689 Instead, an evaluator that enters a locked thunk should be blocked,
3690 and made runnable again when the thunk is updated.
3692 This locking is readily arranged in the same way as black-holing, by
3693 overwriting the thunk's info pointer with a special ``locked'' info
3694 pointer, at the moment of entry. If another evaluator enters the
3695 thunk before it has been updated, it will land in the entry code for
3696 the ``locked'' info pointer, which blocks the evaluator and queues it
3697 on the locked thunk.
3699 The details are given by <.portable parallel trinder.>. However, the close similarity
3700 between locking and black holing suggests the following question: can
3701 locking be done lazily too? The answer is that it can, except that
3702 locking can be postponed only until the next {\em context switch},
3703 rather than the next {\em garbage collection}. We are assuming here
3704 that the parallel implementation does not use shared memory to allow
3705 two processors to access the same closure. If such access is
3706 permitted then every thunk entry requires a hardware lock, and becomes
3709 Is lazy locking worth while, given that it requires extra work every
3710 context switch? We believe it is, because contexts switches are
3711 relatively infrequent, and thousands of thunk-entries typically take
3714 {\em Measurements elsewhere. Omit this section? If so, fix cross refs to here.}
3719 \subsection{Squeezing identical updates}
3723 \ToDo{Insert text stolen from update paper}
3727 Consider the following Haskell definition of the standard
3728 function @partition@ that divides a list into two, those elements
3729 that satisfy a predicate @p@ and those that do not:
3731 partition :: (a->Bool) -> [a] -> ([a],[a])
3732 partition p [] = ([],[])
3733 partition p (x:xs) = if p x then (x:ys, zs)
3736 (ys,zs) = partition p xs
3738 By the time this definition has been desugared, it looks like this:
3748 if p x then (x:ys,zs)
3751 Lazy evaluation demands that the recursive call is bound to an
3752 intermediate variable, @t@, from which @ys@ and @zs@ are lazily
3753 selected. (The functions @fst@ and @snd@ select the first and second
3754 elements of a pair, respectively.)
3756 Now, suppose that @partition@ is applied to a list @[x1,x2]@,
3758 elements satisfy @p@. We can get a good idea of what will happen
3759 at runtime by unrolling the recursion a few times in our heads.
3760 Unrolling once, and remembering that @(p x1)@ is @True@, we get this:
3764 let t1 = partition [x2]
3769 Unrolling the rest of the way gives this:
3781 Now consider what happens if @zs1@ is evaluated. It is bound to a
3782 thunk, which will push an update frame before evaluating the
3783 expression @snd t1@. This expression in turn forces evaluation of
3784 @zs2@, which pushes an update frame before evaluating @snd t2@.
3785 Indeed the stack of update frames will grow as deep as the list is
3786 long when @zs1@ is evaluated. This is rather galling, since all the
3787 thunks @zs1@, @zs2@, and so on, have the same value.
3789 \ToDo{Describe the state-transformer case in which we get a space leak from
3790 pending update frames.}
3792 The solution is simple. The garbage collector, which is going to traverse the
3793 update stack in any case, can easily identify two update frames that are directly
3794 on top of each other. The second of these will update its target with the same
3795 value as the first. Therefore, the garbage collector can perform the update
3796 right away, by overwriting one update target with an indirection to the second,
3797 and eliminate the corresponding update frame. In this way ever-growing stacks of
3798 update frames are reduced to a single representative at garbage collection time.
3799 If this is done at the start of garbage collection then, if it turns out that
3800 some of these update targets are garbage they will be collected right away.
3804 \subsection{Space leaks and selectors}\label{sect:space-leaks-and-selectors}
3808 \ToDo{Insert text stolen from update paper}
3812 In 1987, Wadler identified an important source of space leaks in
3813 lazy functional programs. Consider the Haskell function definition:
3815 f p = (g1 a, g2 b) where (a,b) = p
3817 The pattern-matching in the @where@ clause is known as
3818 {\em lazy pattern-matching}, because it is performed only if @a@
3819 or @b@ is actually evaluated. The desugarer translates lazy pattern matching
3820 to the use of selectors, @fst@ and @snd@ in this case:
3827 Now suppose that the second component of the pair @(f p)@, namely @a@,
3828 is evaluated and discarded, but the first is not although it remains
3829 reachable. The garbage collector will find that the thunk for @b@ refers
3830 to @p@ and hence to @a@. Thus, although @a@ cannot ever be used again, its
3831 space is retained. It turns out that this space leak can have a very bad effect
3832 indeed on a program's space behaviour (Section~\ref{sect:selector-results}).
3834 Wadler's paper also proposed a solution: if the garbage collector
3835 encounters a thunk of the form @snd p@, where @p@ is evaluated, then
3836 the garbage collector should perform the selection and overwrite the
3837 thunk with a pointer to the second component of the pair. In effect, the
3838 garbage collector thereby performs a bounded amount of as-yet-undemanded evaluation
3839 in the hope of improving space behaviour.
3840 We implement this idea directly, by making the garbage collector
3841 eagerly execute all selector thunks\footnote{A word of caution: it is rather easy
3842 to make a mistake in the implementation, especially if the garbage collector
3843 uses pointer reversal to traverse the reachable graph.},
3845 reported in Section~\ref{sect:THUNK_SEL}.
3847 One could easily imagine generalisations of this idea, with the garbage
3848 collector performing bounded amounts of space-saving work. One example is
3852 f x (y:ys) = f (x+1) ys
3854 Most lazy evaluators will build up a chain of thunks for the accumulating
3855 parameter, @x@, each of which increments @x@. It is not safe to evaluate
3856 any of these thunks eagerly, since @f@ is not strict in @x@, and we know nothing
3857 about the value of @x@ passed in the initial call to @f@.
3858 On the other hand, if the garbage collector found a thunk @(x+1)@ where
3859 @x@ happened to be evaluated, then it could ``execute'' it eagerly.
3860 If done carefully, the entire chain could be eliminated in a single
3861 garbage collection. We have not (yet) implemented this idea.
3862 A very similar idea, dubbed ``stingy evaluation'', is described
3865 \ToDo{Simple generalisation: handle all the ``standard closures'' this way.}
3867 <.sparud lazy pattern matching.> describes another solution to the
3868 lazy-pattern-matching
3869 problem. His solution involves adding code to the two thunks for
3870 @a@ and @b@ so that if either is evaluated it arranges to update the
3871 other as well as itself. The garbage-collector solution is a little
3872 more general, since it applies whether or not the selectors were
3873 generated by lazy pattern matching, and in our setting it was easier
3874 to implement than Sparud's.
3879 \subsection{Internal workings of the Compacting Collector}
3881 \subsection{Internal workings of the Copying Collector}
3883 \subsection{Internal workings of the Generational Collector}
3886 \section{Dynamic Linking}
3890 Registering costs centres looks awkward - can we tidy it up?
3892 \section{Parallelism}
3894 Something about global GC, inter-process messages and fetchmes.
3898 \section{Ticky Ticky profiling}
3900 Measure what proportion of ...:
3903 ... Enters are to data values, function values, thunks.
3905 ... allocations are for data values, functions values, thunks.
3907 ... updates are for data values, function values.
3911 ... return-in-heap (dynamic)
3913 ... vectored return (dynamic)
3915 ... updates are wasted (never re-entered).
3917 ... constructor returns get away without hitting an update.
3920 %************************************************************************
3922 \subsubsection[ticky-stk-heap-use]{Stack and heap usage}
3924 %************************************************************************
3926 Things we are interested in here:
3929 How many times we do a heap check and move @Hp@; comparing this with
3930 the allocations gives an indication of how many things we get per trip
3933 If we do a ``heap lookahead,'' we haven't really allocated any
3934 heap, so we need to undo the effects of an @ALLOC_HEAP@:
3937 The stack high-water mark.
3940 Re-use of stack slots, and stubbing of stack slots:
3944 %************************************************************************
3946 \subsubsection[ticky-allocs]{Allocations}
3948 %************************************************************************
3950 We count things every time we allocate something in the dynamic heap.
3951 For each, we count the number of words of (1)~``admin'' (header),
3952 (2)~good stuff (useful pointers and data), and (3)~``slop'' (extra
3953 space, in hopes it will allow an in-place update).
3955 The first five macros are inserted when the compiler generates code
3956 to allocate something; the categories correspond to the @ClosureClass@
3957 datatype (manifest functions, thunks, constructors, big tuples, and
3958 partial applications).
3960 We may also allocate space when we do an update, and there isn't
3961 enough space. These macros suffice (for: updating with a partial
3962 application and a constructor):
3964 In the threaded world, we allocate space for the spark pool, stack objects,
3965 and thread state objects.
3967 The histogrammy bit is fairly straightforward; the @-2@ is: one for
3968 0-origin C arrays; the other one because we do {\em no} one-word
3969 allocations, so we would never inc that histogram slot; so we shift
3970 everything over by one.
3972 Some hard-to-account-for words are allocated by/for primitives,
3973 includes Integer support. @ALLOC_PRIM2@ tells us about these. We
3974 count everything as ``goods'', which is not strictly correct.
3975 (@ALLOC_PRIM@ is the same sort of stuff, but we know the
3976 admin/goods/slop breakdown.)
3978 %************************************************************************
3980 \subsubsection[ticky-enters]{Enters}
3982 %************************************************************************
3984 We do more magical things with @ENT_FUN_DIRECT@. Besides simply knowing
3985 how many ``fast-entry-point'' enters there were, we'd like {\em simple}
3986 information about where those enters were, and the properties thereof.
3988 struct ent_counter {
3989 unsigned registeredp:16, /* 0 == no, 1 == yes */
3990 arity:16, /* arity (static info) */
3991 Astk_args:16, /* # of args off A stack */
3992 Bstk_args:16; /* # of args off B stack */
3993 /* (rest of args are in registers) */
3994 StgChar *f_str; /* name of the thing */
3995 StgChar *f_arg_kinds; /* info about the args types */
3996 StgChar *wrap_str; /* name of its wrapper (if any) */
3997 StgChar *wrap_arg_kinds;/* info about the orig wrapper's arg types */
3998 I_ ctr; /* the actual counter */
3999 struct ent_counter *link; /* link to chain them all together */
4003 %************************************************************************
4005 \subsubsection[ticky-returns]{Returns}
4007 %************************************************************************
4009 Whenever a ``return'' occurs, it is returning the constituent parts of
4010 a data constructor. The parts can be returned either in registers, or
4011 by allocating some heap to put it in (the @ALLOC_*@ macros account for
4012 the allocation). The constructor can either be an existing one
4013 (@*OLD*@) or we could have {\em just} figured out this stuff
4016 Here's some special magic that Simon wants [edited to match names
4020 From: Simon L Peyton Jones <simonpj>
4021 To: partain, simonpj
4022 Subject: counting updates
4023 Date: Wed, 25 Mar 92 08:39:48 +0000
4025 I'd like to count how many times we update in place when actually Node
4026 points to the thing. Here's how:
4028 @RET_OLD_IN_REGS@ sets the variable @ReturnInRegsNodeValid@ to @True@;
4029 @RET_NEW_IN_REGS@ sets it to @False@.
4031 @RET_SEMI_???@ sets it to??? ToDo [WDP]
4033 @UPD_CON_IN_PLACE@ tests the variable, and increments @UPD_IN_PLACE_COPY_ctr@
4036 Then we need to report it along with the update-in-place info.
4040 Of all the returns (sum of four categories above), how many were
4041 vectored? (The rest were obviously unvectored).
4043 %************************************************************************
4045 \subsubsection[ticky-update-frames]{Update frames}
4047 %************************************************************************
4049 These macros count up the following update information.
4051 \begin{tabular}{|l|l|} \hline
4052 Macro & Counts \\ \hline
4054 @UPDF_STD_PUSHED@ & Update frame pushed \\
4055 @UPDF_CON_PUSHED@ & Constructor update frame pushed \\
4056 @UPDF_HOLE_PUSHED@ & An update frame to update a black hole \\
4057 @UPDF_OMITTED@ & A thunk decided not to push an update frame \\
4058 & (all subsets of @ENT_THK@) \\
4059 @UPDF_RCC_PUSHED@ & Cost Centre restore frame pushed \\
4060 @UPDF_RCC_OMITTED@ & Cost Centres not required -- not pushed \\\hline
4063 %************************************************************************
4065 \subsubsection[ticky-updates]{Updates}
4067 %************************************************************************
4069 These macros record information when we do an update. We always
4070 update either with a data constructor (CON) or a partial application
4073 \begin{tabular}{|l|l|}\hline
4074 Macro & Where \\ \hline
4076 @UPD_EXISTING@ & Updating with an indirection to something \\
4077 & already in the heap \\
4078 @UPD_SQUEEZED@ & Same as @UPD_EXISTING@ but because \\
4079 & of stack-squeezing \\
4080 @UPD_CON_W_NODE@ & Updating with a CON: by indirecting to Node \\
4081 @UPD_CON_IN_PLACE@ & Ditto, but in place \\
4082 @UPD_CON_IN_NEW@ & Ditto, but allocating the object \\
4083 @UPD_PAP_IN_PLACE@ & Same, but updating w/ a PAP \\
4084 @UPD_PAP_IN_NEW@ & \\\hline
4087 %************************************************************************
4089 \subsubsection[ticky-selectors]{Doing selectors at GC time}
4091 %************************************************************************
4093 @GC_SEL_ABANDONED@: we could've done the selection, but we gave up
4094 (e.g., to avoid overflowing the C stack); @GC_SEL_MINOR@: did a
4095 selection in a minor GC; @GC_SEL_MAJOR@: ditto, but major GC.
4101 We're nuking the following:
4108 Return in registers.
4109 This lets us remove update code pointers from info tables,
4110 removes the need for phantom info tables, simplifies
4115 Careful analysis suggests that it doesn't buy us very much
4116 and it is hard to work with.
4118 Eliminating threaded GCs eliminates the desire to share SMReps
4119 so they are (once more) part of the Info table.
4123 Doesn't buy us anything on a register-poor architecture and
4124 isn't so important if we have semi-tagging.
4127 - Probably bad on register poor architecture
4128 - Can avoid need to write return address to stack on reg rich arch.
4129 - when a function does a small amount of work, doesn't
4130 enter any other thunks and then returns.
4131 eg entering a known constructor (but semitagging will catch this)
4132 - Adds complications
4138 This lets us drop CONST closures and CHARLIKE closures (assuming we
4139 don't support Unicode). The only point of these closures was to
4140 avoid updating with an indirection.
4142 We also drop @MIN_UPD_SIZE@ --- all we need is space to insert an
4143 indirection or a black hole.
4146 STATIC SMReps are now called CONST
4151 \item The profiling ``kind'' field is now encoded in the @INFO_TYPE@ field.
4152 This identifies the general sort of the closure for profiling purposes.
4154 \item Various papers describe deleting update frames for unreachable objects.
4155 This has never been implemented and we don't plan to anytime soon.
4159 \section{Old tricks}
4163 These are statically defined closures which have been updated with a
4164 heap-allocated result. Initially these are exactly the same as a
4165 @STATIC@ closure but with special entry code. On entering the closure
4166 the entry code must:
4169 \item Allocate a black hole in the heap which will be updated with
4171 \item Overwrite the static closure with a special @CAF@ indirection.
4173 \item Link the static indirection onto the list of updated @CAF@s.
4176 The indirection and the link field require the initial @STATIC@
4177 closure to be of at least size @MIN_UPD_SIZE@ (excluding the fixed
4180 @CAF@s are treated as special garbage collection roots. These roots
4181 are explicitly collected by the garbage collector, since they may
4182 appear in code even if they are not linked with the main heap. They
4183 consequently represent potentially enormous space-leaks. A @CAF@
4184 closure retains a fixed location in statically allocated data space.
4185 When updated, the contents of the @CAF@ indirection are changed to
4186 reflect the new closure. @CAF@ indirections require special garbage
4189 \section{Old stuff about SRTs}
4191 Garbage collection of @CAF@s is tricky. We have to cope with explicit
4192 collection from the @CAFlist@ as well as potential references from the
4193 stack and heap which will cause the @CAF@ evacuation code to be
4194 called. They are treated like indirections which are shorted out.
4195 However they must also be updated to point to the new location of the
4196 new closure as the @CAF@ may still be used by references which
4199 {\bf Copying Collection}
4201 A first scheme might use evacuation code which evacuates the reference
4202 and updates the indirection. This is no good as subsequent evacuations
4203 will result in an already evacuated closure being evacuated. This will
4204 leave a forward reference in to-space!
4206 An alternative scheme evacuates the @CAFlist@ first. The closures
4207 referenced are evacuated and the @CAF@ indirection updated to point to
4208 the evacuated closure. The @CAF@ evacuation code simply returns the
4209 updated indirection pointer --- the pointer to the evacuated closure.
4210 Unfortunately the closure the @CAF@ references may be a static
4211 closure, in fact, it may be another @CAF@. This will cause the second
4212 @CAF@'s evacuation code to be called before the @CAF@ has been
4213 evacuated, returning an unevacuated pointer.
4215 Another scheme leaves updating the @CAF@ indirections to the end of
4216 the garbage collection. All the references are evacuated and
4217 scavenged as usual (including the @CAFlist@). Once collection is
4218 complete the @CAFlist@ is traversed updating the @CAF@ references with
4219 the result of evacuating the referenced closure again. This will
4220 immediately return as it must be a forward reference, a static
4221 closure, or a @CAF@ which will indirect by evacuating its reference.
4223 The crux of the problem is that the @CAF@ evacuation code needs to
4224 know if its reference has already been evacuated and updated. If not,
4225 then the reference can be evacuated, updated and returned safely
4226 (possibly evacuating another @CAF@). If it has, then the updated
4227 reference can be returned. This can be done using two @CAF@
4228 info-tables. At the start of a collection the @CAFlist@ is traversed
4229 and set to an internal {\em evacuate and update} info-table. During
4230 collection, evacution of such a @CAF@ also results in the info-table
4231 being reset back to the standard @CAF@ info-table. Thus subsequent
4232 evacuations will simply return the updated reference. On completion of
4233 the collection all @CAF@s will have {\em return reference} info-tables
4236 This is the scheme we adopt. A @CAF@ indirection has evacuation code
4237 which returns the evacuated and updated reference. During garbage
4238 collection, all the @CAF@s are overwritten with an internal @CAF@ info
4239 table which has evacuation code which performs this evacuate and
4240 update and restores the original @CAF@ code. At some point during the
4241 collection we must ensure that all the @CAF@s are indeed evacuated.
4243 The only potential problem with this scheme is a cyclic list of @CAF@s
4244 all directly referencing (possibly via indirections) another @CAF@!
4245 Evacuation of the first @CAF@ will fail in an infinite loop of @CAF@
4246 evacuations. This is solved by ensuring that the @CAF@ info-table is
4247 updated to a {\em return reference} info-table before performing the
4248 evacuate and update. If this {\em return reference} evacuation code is
4249 called before the actual evacuation is complete it must be because
4250 such a cycle of references exists. Returning the still unevacuated
4251 reference is OK --- all the @CAF@s will now reference the same
4252 @CAF@ which will reference itself! Construction of such a structure
4253 indicates the program must be in an infinite loop.
4255 {\bf Compacting Collector}
4257 When shorting out a @CAF@, its reference must be marked. A first
4258 attempt might explicitly mark the @CAF@s, updating the reference with
4259 the marked reference (possibly short circuting indirections). The
4260 actual @CAF@ marking code can indicate that they have already been
4261 marked (though this might not have actually been done yet) and return
4262 the indirection pointer so it is shorted out. Unfortunately the @CAF@
4263 reference might point to an indirection which will be subsequently
4264 shorted out. Rather than returning the @CAF@ reference we treat the
4265 @CAF@ as an indirection, calling the mark code of the reference, which
4266 will return the appropriately shorted reference.
4268 Problem: Cyclic list of @CAF@s all directly referencing (possibly via
4269 indirections) another @CAF@!
4271 Before compacting, the locations of the @CAF@ references are
4272 explicitly linked to the closures they reference (if they reference
4273 heap allocated closures) so that the compacting process will update
4274 them to the closure's new location. Unfortunately these locations'
4275 @CAF@ indirections are static. This causes premature termination
4276 since the test to find the info pointer at the end of the location
4277 list will match more than one value. This can be solved by using an
4278 auxiliary dynamic array (on the top of the A stack). One location for
4279 each @CAF@ indirection is linked to the closure that the @CAF@
4280 references. Once collection is complete this array is traversed and
4281 the corresponding @CAF@ is then updated with the updated pointer from
4282 the auxiliary array.
4285 It is possible to use an alternative marking scheme, using a similar
4286 idea to the copying solution. This scheme avoids the need to update
4287 the @CAF@ references explicitly. We introduce an auxillary {\em mark
4288 and update} @CAF@ info-table which is used to update all @CAF@s at the
4289 start of a collection. The new code marks the @CAF@ reference,
4290 updating it with the returned reference. The returned reference is
4291 itself returned so the @CAF@ is shorted out. The code also modifies the
4292 @CAF@ info-table to be a {\em return reference}. Subsequent attempts to
4293 mark the @CAF@ simply return the updated reference.
4295 A cyclic @CAF@ reference will result in an attempt to mark the @CAF@
4296 before the marking has been completed and the reference updated. We
4297 cannot start marking the @CAF@ as it is already being marked. Nor can
4298 we return the reference as it has not yet been updated. Neither can we
4299 treat the CAF as an indirection since the @CAF@ reference has been
4300 obscured by the pointer reversal stack. All we can do is return the
4301 @CAF@ itself. This will result in some @CAF@ references not being
4304 This scheme has not been adopted but has been implemented. The code is
4305 commented out with @#if 0@.
4307 \subsection{The virtual register set}
4309 We refer to any (atomic) part of the virtual machine state as a ``register.''
4310 These ``registers'' may be shared between all threads in the system or may be
4311 specific to each thread.
4317 Thread preemption flag
4322 TSO - pointer to the TSO for when we have to pack thread away
4325 Su - used to calculate number of arguments on stack
4326 - this is a more convenient representation
4327 Call/return registers (aka General purpose registers)
4328 Cost centre (and other debug/profile info)
4329 Statistic gathering (not in production system)
4331 Heap overflow - possible global?
4332 Stack overflow - possibly global?
4333 Pattern match failure
4334 maybe a failWith handler?
4335 maybe an exitWith handler?
4339 Some of these virtual ``registers'' are used very frequently and should
4340 be mapped onto machine registers if at all possible. Others are used
4341 very infrequently and can be kept in memory to free up registers for
4344 On register-poor architectures, we can play a few tricks to reduce the
4345 number of virtual registers which need to be accessed on a regular
4350 - Grow stack and heap towards each other (single-threaded system only)
4351 - We might need to keep the C stack pointer in a register if that
4352 is what the OS expects when a signal occurs.
4353 - Preemption flag trick
4354 - If any of the frequently accessed registers cannot be mapped onto
4355 machine registers we should keep the TSO in a machine register to
4356 allow faster access to all the other non-machine registers.