2 % (c) The OBFUSCATION-THROUGH-GRATUITOUS-PREPROCESSOR-ABUSE Project,
3 % Glasgow University, 1990-1994
8 % o I (ADR) 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.
14 % \documentstyle[preprint]{acmconf}
15 \documentclass[11pt]{article}
16 \oddsidemargin 0.1 in % Note that \oddsidemargin = \evensidemargin
17 \evensidemargin 0.1 in
18 \marginparwidth 0.85in % Narrow margins require narrower marginal notes
24 \newcommand{\note}[1]{{\em Note: #1}}
34 \setlength{\parskip}{0.15cm}
35 \setlength{\parsep}{0.15cm}
36 \setlength{\topsep}{0cm} % Reduces space before and after verbatim,
37 % which is implemented using trivlist
38 \setlength{\parindent}{0cm}
40 \renewcommand{\textfraction}{0.2}
41 \renewcommand{\floatpagefraction}{0.7}
45 \newcommand{\ToDo}[1]{{{\bf ToDo:}\sl #1}}
46 \newcommand{\Note}[1]{{{\bf Note:}\sl #1}}
47 \newcommand{\Arg}[1]{\mbox{${\tt arg}_{#1}$}}
48 \newcommand{\bottom}{bottom} % foo, can't remember the symbol name
50 \title{The STG runtime system (revised)}
51 \author{Simon Peyton Jones \\ Glasgow University and Oregon Graduate Institute \and
52 Simon Marlow \\ Glasgow University \and
53 Alastair Reid \\ Yale University}
63 This document describes the GHC/Hugs run-time system. It serves as
64 a Glasgow/Yale/Nottingham ``contract'' about what the RTS does.
66 \subsection{New features compared to GHC 2.04}
69 \item The RTS supports mixed compiled/interpreted execution, so
70 that a program can consist of a mixture of GHC-compiled and Hugs-interpreted
73 \item CAFs are only retained if they are
74 reachable. Since they are referred to by implicit references buried
75 in code, this means that the garbage collector must traverse the whole
76 accessible code tree. This feature eliminates a whole class of painful
79 \item A running thread has only one stack, which contains a mixture
80 of pointers and non-pointers. Section~\ref{sect:stacks} describes how
81 we find out which is which. (GHC has used two stacks for some while.
82 Using one stack instead of two reduces register pressure, reduces the
83 size of update frames, and eliminates
84 ``stack-stubbing'' instructions.)
86 \item The ``return in registers'' return convention has been dropped
87 because it was complicated and doesn't work well on register-poor
88 architectures. It has been partly replaced by unboxed tuples
89 (section~\ref{sect:unboxed-tuples}) which allow the programmer to
90 explicitly state where results should be returned in registers (or on
91 the stack) instead of on the heap.
95 Lazy black-holing has been replaced by eager black-holing. The
96 problem with lazy black-holing is that it leaves slop in the heap
97 which conflicts with the use of a mostly-copying collector.
101 \subsection{Wish list}
103 Here's a list of things we'd like to support in the future.
105 \item Interrupts, speculative computation.
108 The SM could tune the size of the allocation arena, the number of
109 generations, etc taking into account residency, GC rate and page fault
113 There should be no need to specify the amnount of stack/heap space to
114 allocate when you started a program - let it just take as much or as
115 little as it wants. (It might be useful to be able to specify maximum
116 sizes and to be able to suggest an initial size.)
119 We could trigger a GC when all threads are blocked waiting for IO if
120 the allocation arena (or some of the generations) are nearly full.
124 \subsection{Configuration}
126 Some of the above features are expensive or less portable, so we
127 envision building a number of different configurations supporting
128 different subsets of the above features.
130 You can make the following choices:
133 Support for concurrency or parallelism. There are four
134 mutually-exclusive choices.
137 \item[@SEQUENTIAL@] No concurrency or parallelism support.
138 This configuration might not support interrupt recovery.
140 \note{There's probably not much point in supporting this option. If
141 we've gone to the effort of supporting concurency, we don't gain
142 much by being able to turn it off.}
144 \item[@CONCURRENT@] Support for concurrency but not for parallelism.
145 \item[@CONCURRENT@+@GRANSIM@] Concurrency support and simulated parallelism.
146 \item[@CONCURRENT@+@PARALLEL@] Concurrency support and real parallelism.
149 \item @PROFILING@ adds cost-centre profiling.
151 \item @TICKY@ gathers internal statistics (often known as ``ticky-ticky'' code).
153 \item @DEBUG@ does internal consistency checks.
155 \item Persistence. (well, not yet).
158 Which garbage collector to use. At the moment we
159 only anticipate one, however.
162 \subsection{Glossary}
164 \ToDo{This terminology is not used consistently within the document.
165 If you find something which disagrees with this terminology, fix the
170 \item A {\em word} is (at least) 32 bits and can hold either a signed
173 \item A {\em pointer} is (at least) 32 bits and big enough to hold a
174 function pointer or a data pointer.
176 \item A {\em boxed} type is one whose elements are heap allocated.
178 \item An {\em unboxed} type is one whose elements are {\em not} heap allocated.
180 \item A {\em pointed} type is one that contains $\bot$. Variables with
181 pointed types are the only things which can be lazily evaluated. In
182 the STG machine, this means that they are the only things that can be
183 {\em entered} or {\em updated} and it requires that they be boxed.
185 \item An {\em unpointed} type is one that does not contain $\bot$.
186 Variables with unpointed types are never delayed --- they are always
187 evaluated when they are constructed. In the STG machine, this means
188 that they cannot be {\em entered} or {\em updated}. Unpointed objects
189 may be boxed (like @Array#@) or unboxed (like @Int#@).
191 \item A {\em closure} is a (representation of) a value of a {\em pointed}
192 type. It may be in HNF or it may be unevaluated --- in either case, you can
193 try to evaluate it again.
195 \item A {\em thunk} is a (representation of) a value of a {\em pointed}
196 type which is {\em not} in HNF.
198 \item A {\em value} is an object in HNF. It can be pointed or unpointed.
202 Occasionally, a field of a data structure must hold either a word or a
203 pointer. In such circumstances, it is {\em not safe} to assume that
204 words and pointers are the same size.
207 % More terminology to mention.
210 \subsection{Subtle Dependencies}
212 Some decisions have very subtle consequences which should be written
213 down in case we want to change our minds.
217 \item The garbage collector never expands an object when it promotes
218 it to the old generation. This is important because the GC avoids
219 performing heap overflow checks by assuming that the amount added to
220 the old generation is no bigger than the current new generation.
224 If the garbage collector is allowed to shrink the stack of a thread,
225 we cannot omit the stack check in return continuations
226 (section~\ref{sect:heap-and-stack-checks}).
230 When we return to the scheduler, the top object on the stack is a closure.
231 The scheduler restarts the thread by entering the closure.
233 Section~\ref{sect:hugs-return-convention} discusses how Hugs returns an
234 unboxed value to GHC and how GHC returns an unboxed value to Hugs.
238 When we return to the scheduler, we need a few empty words on the stack
239 to store a closure to reenter. Section~\ref{sect:heap-and-stack-checks}
240 discusses who does the stack check and how much space they need.
244 Heap objects never contain slop --- this is required if we want to
245 support mostly-copying garbage collection.
247 This is a big problem when updating since the updatee is usually
248 bigger than an indirection object. The fix is to overwrite the end of
249 the updatee with ``slop objects'' (described in
250 section~\ref{sect:slop-objects}).
251 This is hard to arrange if we do \emph{lazy} blackholing
252 (section~\ref{sect:lazy-black-holing}) so we currently plan to
253 blackhole an object when we push the update frame.
259 Info tables for constructors contain enough information to decide which
260 return convention they use. This allows Hugs to use a single piece of
261 entry code for all constructors and insulates Hugs from changes in the
262 choice of return convention.
266 \section{Source Language}
268 \subsection{Explicit Allocation}\label{sect:explicit-allocation}
270 As in the original STG machine, (almost) all heap allocation is caused
271 by executing a let(rec). Since we no longer support the return in
272 registers convention for data constructors, constructors now cause heap
273 allocation and so they should be let-bound.
275 For example, we now write
277 > cons = \ x xs -> let r = (:) x xs in r
281 > cons = \ x xs -> (:) x xs
285 \subsection{Unboxed tuples}\label{sect:unboxed-tuples}
287 Functions can take multiple arguments as easily as they can take one
288 argument: there's no cost for adding another argument. But functions
289 can only return one result: the cost of adding a second ``result'' is
290 that the function must construct a tuple of ``results'' on the heap.
291 The assymetry is rather galling and can make certain programming
292 styles quite expensive. For example, consider a simple state transformer
295 > type S a = State -> (a,State)
296 > bindS m k s0 = case m s0 of { (a,s1) -> k a s1 }
297 > returnS a s = (a,s)
301 Here, every use of @returnS@, @getS@ or @setS@ constructs a new tuple
302 in the heap which is instantly taken apart (and becomes garbage) by
303 the case analysis in @bind@. Even a short state-transformer program
304 will construct a lot of these temporary tuples.
306 Unboxed tuples provide a way for the programmer to indicate that they
307 do not expect a tuple to be shared and that they do not expect it to
308 be allocated in the heap. Syntactically, unboxed tuples are just like
309 single constructor datatypes except for the annotation @unboxed@.
311 > data unboxed AAndState# a = AnS a State
312 > type S a = State -> AAndState# a
313 > bindS m k s0 = case m s0 of { AnS a s1 -> k a s1 }
314 > returnS a s = AnS a s
316 > setS s _ = AnS () s
318 Semantically, unboxed tuples are just unlifted tuples and are subject
319 to the same restrictions as other unpointed types.
321 Operationally, unboxed tuples are never built on the heap. When
322 unboxed tuples are returned, they are returned in multiple registers
323 or multiple stack slots. At first sight, this seems a little strange
324 but it's no different from passing double precision floats in two
330 Unboxed tuples can only have one constructor and that
331 thunks never have unboxed types --- so we'll never try to update an
332 unboxed constructor. The restriction to a single constructor is
333 largely to avoid garbage collection complications.
336 The core syntax does not allow variables to be bound to
337 unboxed tuples (ie in default case alternatives or as function arguments)
338 and does not allow unboxed tuples to be fields of other constructors.
339 However, there's no harm in allowing it in the source syntax as a
340 convenient, but easily removed, syntactic sugar.
343 The compiler generates a closure of the form
345 > c = \ x y z -> C x y z
347 for every constructor (whether boxed or unboxed).
349 This closure is normally used during desugaring to ensure that
350 constructors are saturated and to apply any strictness annotations.
351 They are also used when returning unboxed constructors to the machine
352 code evaluator from the bytecode evaluator and when a heap check fails
353 in a return continuation for an unboxed-tuple scrutinee.
357 \subsection{STG Syntax}
359 \ToDo{Insert STG syntax with appropriate changes.}
362 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
363 \part{System Overview}
364 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
366 This part is concerned with defining the external interfaces of the
367 major components of the system; the next part is concerned with their
370 The major components of the system are:
373 \item The storage manager
379 \ToDo{Insert diagram showing all components underneath the scheduler
380 and communicating only with the scheduler}
384 The Scheduler is the heart of the run-time system. A running program
385 consists of a single running thread, and a list of runnable and
386 blocked threads. All threads consist of a stack and a few words of
387 status information. Except for the running thread, all threads have a
388 closure on top of their stack; the scheduler restarts a thread by
389 entering an evaluator which performs some reduction and returns.
391 \subsection{The scheduler's main loop}
393 The scheduler consists of a loop which chooses a runnable thread and
394 invokes one of the evaluators which performs some reduction and
397 The scheduler also takes care of system-wide issues such as heap
398 overflow or communication with other processors (in the parallel
399 system) and thread-specific problems such as stack overflow.
401 \subsection{Creating a thread}
409 When the scheduler is first invoked.
413 When a message is received from another processor (I think). (Parallel
418 When a C program calls some Haskell code.
423 \subsection{Restarting a thread}
425 The evaluators can reduce almost all types of closure except that only
426 the machine code evaluator can reduce GHC-compiled closures and only
427 the bytecode evaluator can reduce Hugs-compiled closures.
428 Consequently, the scheduler may use either evaluator to restart a
429 thread unless the top closure is a @BCO@ or contains machine code.
431 However, if the top of the stack contains a constructor, the scheduler
432 should use the machine code evaluator to restart the thread. This
433 allows the bytecode evaluator to return a constructor to a machine
434 code return address by pushing the constructor on top of the stack and
435 returning to the scheduler. If the return address under the
436 constructor is @HUGS_RET@, the entry code for @HUGS_RET@ will
437 rearrange the stack so that the return @BCO@ is on top of the stack
438 and return to the scheduler which will then call the bytecode
439 evaluator. There is little point in trying to shorten this slightly
440 indirect route since it will happen very rarely if at all.
442 \subsection{Returning from a thread}
444 The evaluators return to the scheduler when any of the following
448 \item A heap check fails, and a garbage collection is required
449 \item Compiled code needs to switch to interpreted code, and vice versa.
450 \item The evaluator needs to perform an ``unsafe'' C call.
451 \item The thread becomes blocked.
452 \item The thread is preempted.
453 \item The thread terminates.
456 Except when the thread terminates, the thread always terminates with a
457 closure on the top of the stack.
459 \subsection{Preempting a thread}
461 Strictly speaking, threads cannot be preempted --- the scheduler
462 merely sets a preemption request flag which the thread must arrange to
463 test on a regular basis. When an evaluator finds that the preemption
464 request flag is set, it pushes an appropriate closure onto the stack
465 and returns to the scheduler.
467 In the bytecode interpreter, the flag is tested whenever we enter a
468 closure. If the preemption flag is set, it leaves the closure on top
469 of the stack and returns to the scheduler.
471 In the machine code evaluator, the flag is only tested when a heap or
472 stack check fails. This is less expensive than testing the flag on
473 entering every closure but runs the risk that a thread will enter an
474 infinite loop which does not allocate any space. If the flag is set,
475 the evaluator returns to the scheduler exactly as if a heap check had
478 \subsection{``Safe'' and ``unsafe'' C calls}
480 There are two ways of calling C:
484 \item[``Safe'' C calls]
485 are used if the programer is certain that the C function will not
486 do anything dangerous such as calling a Haskell function or an
487 operating system call which blocks the thread for a long period of time.
488 \footnote{Warning: this use of ``safe'' and ``unsafe'' is the exact
489 opposite of the usage for functions like @unsafePerformIO@.}
490 Safe C calls are faster but must be hand-checked by the programmer.
492 Safe C calls are performed by pushing the arguments onto the C stack
493 and jumping to the C function's entry point. On exit, the result of
494 the function is in a register which is returned to the Haskell code as
497 \item[``Unsafe'' C calls] are used if the programmer suspects that the
498 thread may do something dangerous like blocking or calling a Haskell
499 function. Unsafe C calls are relatively slow but are less problematic.
501 Unsafe C calls are performed by pushing the arguments onto the Haskell
502 stack, pushing a return continuation and returning a \emph{C function
503 descriptor} to the scheduler. The scheduler suspends the Haskell thread,
504 spawns a new operating system thread which pops the arguments off the
505 Haskell stack onto the C stack, calls the C function, pushes the
506 function result onto the Haskell stack and informs the scheduler that
507 the C function has completed and the Haskell thread is now runnable.
511 The bytecode evaluator will probably treat all C calls as being unsafe.
513 \ToDo{It might be good for the programmer to indicate how the program is
514 unsafe. For example, if we distinguish between C functions which might
515 call Haskell functions and those which might block, we could perform a
516 safe call for blocking functions in a single-threaded system or, perhaps, in a multi-threaded system which only happens to have a single thread at the moment.}
519 \section{The Evaluators}
521 All the scheduler needs to know about evaluation is how to manipulate
522 threads and how to find the closure on top of the stack. The
523 evaluators need to agree on the representations of certain objects and
524 on how to return from the scheduler.
526 \subsection{Returning to the Scheduler}
527 \label{sect:switching-worlds}
529 The evaluators return to the scheduler under three circumstances:
534 When they enter a closure built by the other evaluator. That is, when
535 the bytecode interpreter enters a closure compiled by GHC or when the
536 machine code evaluator enters a BCO.
540 When they return to a return continuation built by the other
541 evaluator. That is, when the machine code evaluator returns to a
542 continuation built by Hugs or when the bytecode evaluator returns to a
543 continuation built by GHC.
547 When a heap or stack check fails or when the preemption flag is set.
551 In all cases, they return to the scheduler with a closure on top of
552 the stack. The mechanism used to trigger the world switch and the
553 choice of closure left on top of the stack varies according to which
554 world is being left and what is being returned.
556 \subsubsection{Leaving the bytecode evaluator}
557 \label{sect:hugs-to-ghc-switch}
559 \paragraph{Entering a machine code closure}
561 When it enters a closure, the bytecode evaluator performs a switch
562 based on the type of closure (@AP@, @PAP@, @Ind@, etc). On entering a
563 machine code closure, it returns to the scheduler with the closure on
566 \paragraph{Returning a constructor}
568 When it enters a constructor, the bytecode evaluator tests the return
569 continuation on top of the stack. If it is a machine code
570 continuation, it returns to the scheduler with the constructor on top
573 \note{This is why the scheduler must enter the machine code evaluator
574 if it finds a constructor on top of the stack.}
576 \paragraph{Returning an unboxed value}
578 \note{Hugs doesn't support unboxed values in source programs but they
579 are used for a few complex primops.}
581 When it enters a constructor, the bytecode evaluator tests the return
582 continuation on top of the stack. If it is a machine code
583 continuation, it returns to the scheduler with the unboxed value and a
584 special closure on top of the stack. When the closure is entered (by
585 the machine code evaluator), it returns the unboxed value on top of
586 the stack to the return continuation under it.
588 The runtime system (or GHC?) provides one of these closures for each
589 unboxed type. Hugs cannot generate them itself since the entry code is
592 \paragraph{Heap/Stack overflow and preemption}
594 The bytecode evaluator tests for heap/stack overflow and preemption
595 when entering a BCO and simply returns with the BCO on top of the
598 \subsubsection{Leaving the machine code evaluator}
599 \label{sect:ghc-to-hugs-switch}
601 \paragraph{Entering a BCO}
603 The entry code for a BCO pushes the BCO onto the stack and returns to
606 \paragraph{Returning a constructor}
608 We avoid the need to test return addresses in the machine code
609 evaluator by pushing a special return address on top of a pointer to
610 the bytecode return continuation. Figure~\ref{fig:hugs-return-stack}
611 shows the state of the stack just before evaluating the scrutinee.
623 %\input{hugs_return1.pstex_t}
625 \caption{Stack layout for evaluating a scrutinee}
626 \label{fig:hugs-return-stack}
629 This return address rearranges the stack so that the bco pointer is
630 above the constructor on the stack (as shown in
631 figure~\ref{fig:hugs-boxed-return}) and returns to the scheduler.
638 | con |--> Constructor
643 %\input{hugs_return2.pstex_t}
645 \caption{Stack layout for entering a Hugs return address}
646 \label{fig:hugs-boxed-return}
649 \paragraph{Returning an unboxed value}
651 We avoid the need to test return addresses in the machine code
652 evaluator by pushing a special return address on top of a pointer to
653 the bytecode return continuation. This return address rearranges the
654 stack so that the bco pointer is above the unboxed value (as shown in
655 figure~\ref{fig:hugs-entering-unboxed-return}) and returns to the scheduler.
669 %\input{hugs_return2.pstex_t}
671 \caption{Stack layout for returning an unboxed value}
672 \label{fig:hugs-entering-unboxed-return}
675 \paragraph{Heap/Stack overflow and preemption}
679 \subsection{Shared Representations}
681 We share @AP@s, @PAP@s, constructors, indirections, selectors(?) and
682 update frames. These are described in section~\ref{sect:heap-objects}.
685 \section{The Storage Manager}
687 The storage manager is responsible for managing the heap and all
688 objects stored in it. Most objects are just copied in the normal way
689 but a number receive special treatment by the storage manager:
694 Indirections are shorted out.
698 Weak pointers and stable pointers are treated specially.
702 Thread State Objects (TSOs) and the stacks within them are treated specially.
708 Update frames pointing to unreachable objects are squeezed out.
712 Adjacent update frames (for different closures) are compressed to a
713 single update frame pointing to a single black hole.
717 If the stack contains a large amount of free space, the storage
718 manager may shrink the stack. If it shrinks the stack, it guarantees
719 never to leave less than @MIN_SIZE_SHRUNKEN_STACK@ empty words on the
720 stack when it does so.
722 \ToDo{Would it be useful for the storage manager to enlarge the stack?}
728 Very large objects (eg large arrays and TSOs) are not moved if
734 \section{The Compilers}
736 Need to describe interface files, format of bytecode files, symbols
737 defined by machine code files.
739 \subsection{Interface Files}
741 Here's an example - but I don't know the grammar - ADR.
747 1 main _:_ IOBase.IO PrelBase.();;
750 \subsection{Bytecode files}
752 (All that matters here is what the loader sees.)
754 \subsection{Machine code files}
756 (Again, all that matters is what the loader sees.)
759 \subsection{Bytecode files}
761 (All that matters here is what the loader sees.)
763 \subsection{Machine code files}
765 (Again, all that matters is what the loader sees.)
770 \ToDo{Is it ok to load code when threads are running?}
772 In a batch mode system, we can statically link all the modules
773 together. In an interactive system we need a loader which will
774 explicitly load and unload individual modules (or, perhaps, blocks of
775 mutually dependent modules) and resolve references between modules.
777 While many operating systems provide support for dynamic loading and
778 will automatically resolve cross-module references for us, we generally
779 cannot rely on being able to load mutually dependent modules.
781 A portable solution is to perform some of the linking ourselves. Each module
782 should provide three global symbols:
785 An initialisation routine. (Might also be used for finalisation.)
787 A table of symbols it exports.
788 Entries in this table consist of the symbol name and the address of the
791 A table of symbols it imports.
792 Entries in this table consist of the symbol name and a list of references
796 On loading a group of modules, the loader adds the contents of the
797 export lists to a symbol table and then fills in all the references in the
800 References in import lists are of two types:
802 \item[ References in machine code ]
804 The most efficient approach is to patch the machine code directly, but
805 this will be a lot of work, very painful to port and rather fragile.
807 Alternatively, the loader could store the value of each symbol in the
808 import table for each module and the compiled code can access all
809 external objects through the import table. This requires that the
810 import table be writable but does not require that the machine code or
811 info tables be writable.
813 \item[ References in data structures (SRTs and static data constructors) ]
815 Either we patch the SRTs and constructors directly or we somehow use
816 indirections through the symbol table. Patching the SRTs requires
817 that we make them writable and prevents us from making effective use
818 of virtual memories that use copy-on-write policies. Using an
819 indirection is possible but tricky.
821 Note: We could avoid patching machine code if all references to
822 eternal references went through the SRT --- then we just have one
823 thing to patch. But the SRT always contains a pointer to the closure
824 rather than the fast entry point (say), so we'd take a big performance
829 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
830 \part{Internal details}
831 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
833 This part is concerned with the internal details of the components
834 described in the previous part.
836 The major components of the system are:
839 \item The storage manager
845 \section{The Scheduler}
847 \section{The Storage Manager}
848 \label{sect:storage-manager-internals}
850 \ToDo{Fix this picture}
860 Every {\em heap object} is a contiguous block
861 of memory, consisting of a fixed-format {\em header} followed
862 by zero or more {\em data words}.
864 \ToDo{I absolutely do not believe that every heap object has a header
865 like this - ADR. I believe that they all have an info pointer but I
866 see no readon why stack objects and unpointed heap objects would have
867 an entry count since this will always be zero.}
869 The header consists of the following fields:
871 \item A one-word {\em info pointer}, which points to
872 the object's static {\em info table}.
873 \item Zero or more {\em admin words} that support
875 \item Profiling (notably a {\em cost centre} word).
876 \note{We could possibly omit the cost centre word from some
877 administrative objects.}
878 \item Parallelism (e.g. GranSim keeps the object's global address here,
879 though GUM keeps a separate hash table).
880 \item Statistics (e.g. a word to track how many times a thunk is entered.).
882 We add a Ticky word to the fixed-header part of closures. This is
883 used to indicate if a closure has been updated but not yet entered. It
884 is set when the closure is updated and cleared when subsequently
887 NB: It is {\em not} an ``entry count'', it is an
888 ``entries-after-update count.'' The commoning up of @CONST@,
889 @CHARLIKE@ and @INTLIKE@ closures is turned off(?) if this is
890 required. This has only been done for 2s collection.
895 Most of the RTS is completely insensitive to the number of admin words.
896 The total size of the fixed header is @FIXED_HS@.
898 Many heap objects contain fields allowing them to be inserted onto lists
899 during evaluation or during garbage collection. The lists required by
900 the evaluator and storage manager are as follows.
903 \item 2 lists of threads: runnable threads and sleeping threads.
905 \item The {\em static object list} is a list of all statically
906 allocated objects which might contain pointers into the heap.
907 (Section~\ref{sect:static-objects}.)
909 \item The {\em updated thunk list} is a list of all thunks in the old
910 generation which have been updated with an indirection.
911 (Section~\ref{sect:IND_OLDGEN}.)
913 \item The {\em mutables list} is a list of all other objects in the
914 old generation which might contain pointers into the new generation.
915 Most of the object on this list are ``mutable.''
916 (Section~\ref{sect:mutables}.)
918 \item The {\em Foreign Object list} is a list of all foreign objects
919 which have not yet been deallocated. (Section~\ref{sect:FOREIGN}.)
921 \item The {\em Spark pool} is a doubly(?) linked list of Spark objects
922 maintained by the parallel system. (Section~\ref{sect:SPARK}.)
924 \item The {\em Blocked Fetch list} (or
925 lists?). (Section~\ref{sect:BLOCKED_FETCH}.)
927 \item For each thread, there is a list of all update frames on the
928 stack. (Section~\ref{sect:data-updates}.)
933 \ToDo{The links for these fields are usually inserted immediately
934 after the fixed header except ...}
936 \subsection{Info Tables}
938 An {\em info table} is a contiguous block of memory, {\em laid out
939 backwards}. That is, the first field in the list that follows
940 occupies the highest memory address, and the successive fields occupy
941 successive decreasing memory addresses.
945 \hline Parallelism Info
946 \\ \hline Profile Info
948 \\ \hline Tag / Static reference table
949 \\ \hline Storage manager layout info
950 \\ \hline Closure type
955 An info table has the following contents (working backwards in memory
958 \item The {\em entry code} for the closure.
959 This code appears literally as the (large) last entry in the
960 info table, immediately preceded by the rest of the info table.
961 An {\em info pointer} always points to the first byte of the entry code.
963 \item A one-word {\em closure type field}, @INFO_TYPE@, identifies what kind
964 of closure the object is. The various types of closure are described
965 in Section~\ref{sect:closures}.
966 In some configurations, some useful properties of
967 closures (is it a HNF? can it be sparked?)
968 are represented as high-order bits so they can be tested quickly.
970 \item A single pointer or word --- the {\em storage manager info field},
971 @INFO_SM@, contains auxiliary information describing the closure's
972 precise layout, for the benefit of the garbage collector and the code
973 that stuffs graph into packets for transmission over the network.
975 \item A one-word {\em Tag/Static Reference Table} field, @INFO_SRT@.
976 For data constructors, this field contains the constructor tag, in the
977 range $0..n-1$ where $n$ is the number of constructors. For all other
978 objects it contains a pointer to a table which enables the garbage
979 collector to identify all accessible code and CAFs. They are fully
980 described in Section~\ref{sect:srt}.
982 \item {\em Profiling info\/}
984 \ToDo{The profiling info is completely bogus. I've not deleted it
985 from the document but I've commented it all out.}
987 % change to \iftrue to uncomment this section
990 Closure category records are attached to the info table of the
991 closure. They are declared with the info table. We put pointers to
992 these ClCat things in info tables. We need these ClCat things because
993 they are mutable, whereas info tables are immutable. Hashing will map
994 similar categories to the same hash value allowing statistics to be
995 grouped by closure category.
997 Cost Centres and Closure Categories are hashed to provide indexes
998 against which arbitrary information can be stored. These indexes are
999 memoised in the appropriate cost centre or category record and
1000 subsequent hashes avoided by the index routine (it simply returns the
1003 There are different features which can be hashed allowing information
1004 to be stored for different groupings. Cost centres have the cost
1005 centre recorded (using the pointer), module and group. Closure
1006 categories have the closure description and the type
1007 description. Records with the same feature will be hashed to the same
1010 The initialisation routines, @init_index_<feature>@, allocate a hash
1011 table in which the cost centre / category records are stored. The
1012 lower bound for the table size is taken from @max_<feature>_no@. They
1013 return the actual table size used (the next power of 2). Unused
1014 locations in the hash table are indicated by a 0 entry. Successive
1015 @init_index_<feature>@ calls just return the actual table size.
1017 Calls to @index_<feature>@ will insert the cost centre / category
1018 record in the @<feature>@ hash table, if not already inserted. The hash
1019 index is memoised in the record and returned.
1021 CURRENTLY ONLY ONE MEMOISATION SLOT IS AVILABLE IN EACH RECORD SO
1022 HASHING CAN ONLY BE DONE ON ONE FEATURE FOR EACH RECORD. This can be
1023 easily relaxed at the expense of extra memoisation space or continued
1026 The initialisation routines must be called before initialisation of
1027 the stacks and heap as they require to allocate storage. It is also
1028 expected that the caller may want to allocate additional storage in
1029 which to store profiling information based on the return table size
1033 \begin{tabular}{|l|}
1037 \\ \hline Description String
1038 \\ \hline Type String
1044 \item[Hash Index] Memoised copy
1046 Is this category selected (-1 == not memoised, selected? 0 or 1)
1048 One of the following values (defined in CostCentre.lh):
1056 A partial application.
1058 A thunk, or suspension.
1063 \item[@ForeignObj_K@]
1064 A Foreign object (non-Haskell heap resident).
1066 The Stable Pointer table. (There should only be one of these but it
1067 represents a form of weak space leak since it can't shrink to meet
1068 non-demand so it may be worth watching separately? ADR)
1069 \item[@INTERNAL_KIND@]
1070 Something internal to the runtime system.
1074 \item[Description] Source derived string detailing closure description.
1075 \item[Type] Source derived string detailing closure type.
1078 \fi % end of commented out stuff
1080 \item {\em Parallelism info\/}
1083 \item {\em Debugging info\/}
1089 %-----------------------------------------------------------------------------
1090 \subsection{Kinds of Heap Object}
1091 \label{sect:closures}
1093 Heap objects can be classified in several ways, but one useful one is
1097 {\em Static closures} occupy fixed, statically-allocated memory
1098 locations, with globally known addresses.
1101 {\em Dynamic closures} are individually allocated in the heap.
1104 {\em Stack closures} are closures allocated within a thread's stack
1105 (which is itself a heap object). Unlike other closures, there are
1106 never any pointers to stack closures. Stack closures are discussed in
1107 Section~\ref{sect:stacks}.
1110 A second useful classification is this:
1113 {\em Executive objects}, such as thunks and data constructors,
1114 participate directly in a program's execution. They can be subdivided into
1115 three kinds of objects according to their type:
1118 {\em Pointed objects}, represent values of a {\em pointed} type
1119 (<.pointed types launchbury.>) --i.e.~a type that includes $\bottom$ such as @Int@ or @Int# -> Int#@.
1121 \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#@.
1123 \item {\em Activation frames}, represent ``continuations''. They are
1124 always stored on the stack and are never pointed to by heap objects or
1125 passed as arguments. \note{It's not clear if this will still be true
1126 once we support speculative evaluation.}
1130 \item {\em Administrative objects}, such as stack objects and thread
1131 state objects, do not represent values in the original program.
1134 Only pointed objects can be entered. All pointed objects share a
1135 common header format: the ``pointed header''; while all unpointed
1136 objects share a common header format: the ``unpointed header''.
1137 \ToDo{Describe the difference and update the diagrams to mention
1138 an appropriate header type.}
1140 This section enumerates all the kinds of heap objects in the system.
1141 Each is identified by a distinct @INFO_TYPE@ tag in its info table.
1143 \begin{tabular}{|l|l|l|l|l|l|l|l|l|l|l|}
1146 closure kind & Section \\
1152 @CONSTR@ & \ref{sect:CONSTR} \\
1153 @CONSTR_STATIC@ & \ref{sect:CONSTR} \\
1154 @CONSTR_STATIC_NOCAF@ & \ref{sect:CONSTR} \\
1156 @FUN@ & \ref{sect:FUN} \\
1157 @FUN_STATIC@ & \ref{sect:FUN} \\
1159 @THUNK@ & \ref{sect:THUNK} \\
1160 @THUNK_STATIC@ & \ref{sect:THUNK} \\
1161 @THUNK_SELECTOR@ & \ref{sect:THUNK_SEL} \\
1163 @BCO@ & \ref{sect:BCO} \\
1164 @BCO_CAF@ & \ref{sect:BCO} \\
1166 @AP@ & \ref{sect:AP} \\
1167 @PAP@ & \ref{sect:PAP} \\
1169 @IND@ & \ref{sect:IND} \\
1170 @IND_OLDGEN@ & \ref{sect:IND} \\
1171 @IND_PERM@ & \ref{sect:IND} \\
1172 @IND_OLDGEN_PERM@ & \ref{sect:IND} \\
1173 @IND_STATIC@ & \ref{sect:IND} \\
1179 @ARR_WORDS@ & \ref{sect:ARR_WORDS1},\ref{sect:ARR_WORDS2} \\
1180 @ARR_PTRS@ & \ref{sect:ARR_PTRS} \\
1181 @MUTVAR@ & \ref{sect:MUTVAR} \\
1182 @MUTARR_PTRS@ & \ref{sect:MUTARR_PTRS} \\
1183 @MUTARR_PTRS_FROZEN@ & \ref{sect:MUTARR_PTRS_FROZEN} \\
1185 @FOREIGN@ & \ref{sect:FOREIGN} \\
1187 @BH@ & \ref{sect:BH} \\
1188 @MVAR@ & \ref{sect:MVAR} \\
1189 @IVAR@ & \ref{sect:IVAR} \\
1190 @FETCHME@ & \ref{sect:FETCHME} \\
1194 Activation frames do not live (directly) on the heap --- but they have
1195 a similar organisation.
1197 \begin{tabular}{|l|l|}\hline
1198 closure kind & Section \\ \hline
1199 @RET_SMALL@ & \ref{sect:activation-records} \\
1200 @RET_VEC_SMALL@ & \ref{sect:activation-records} \\
1201 @RET_BIG@ & \ref{sect:activation-records} \\
1202 @RET_VEC_BIG@ & \ref{sect:activation-records} \\
1203 @UPDATE_FRAME@ & \ref{sect:activation-records} \\
1207 There are also a number of administrative objects.
1209 \begin{tabular}{|l|l|}\hline
1210 closure kind & Section \\ \hline
1211 @TSO@ & \ref{sect:TSO} \\
1212 @STACK_OBJECT@ & \ref{sect:STACK_OBJECT} \\
1213 @STABLEPTR_TABLE@ & \ref{sect:STABLEPTR_TABLE} \\
1214 @SPARK_OBJECT@ & \ref{sect:SPARK} \\
1215 @BLOCKED_FETCH@ & \ref{sect:BLOCKED_FETCH} \\
1219 \ToDo{I guess the parallel system has something like a stable ptr
1220 table. Is there any opportunity for sharing code/data structures
1224 \subsection{Predicates}
1226 \ToDo{The following is a first attempt at defining a useful set of
1227 predicates. Some (such as @isWHNF@ and @isSparkable@) may need their
1228 definitions tweaked a little.}
1230 The runtime system sometimes needs to be able to distinguish objects
1231 according to their properties: is the object updateable? is it in weak
1232 head normal form? etc. These questions can be answered by examining
1233 the @INFO_TYPE@ field of the object's info table.
1235 We define the following predicates to detect families of related
1236 info types. They are mutually exclusive and exhaustive.
1239 \item @isCONSTR@ is true for @CONSTR@s.
1240 \item @isFUN@ is true for @FUN@s.
1241 \item @isTHUNK@ is true for @THUNK@s.
1242 \item @isBCO@ is true for @BCO@s.
1243 \item @isAP@ is true for @AP@s.
1244 \item @isPAP@ is true for @PAP@s.
1245 \item @isINDIRECTION@ is true for indirection objects.
1246 \item @isBH@ is true for black holes.
1247 \item @isFOREIGN_OBJECT@ is true for foreign objects.
1248 \item @isARRAY@ is true for array objects.
1249 \item @isMVAR@ is true for @MVAR@s.
1250 \item @isIVAR@ is true for @IVAR@s.
1251 \item @isFETCHME@ is true for @FETCHME@s.
1252 \item @isSLOP@ is true for slop objects.
1253 \item @isRET_ADDR@ is true for return addresses.
1254 \item @isUPD_ADDR@ is true for update frames.
1255 \item @isTSO@ is true for @TSO@s.
1256 \item @isSTABLE_PTR_TABLE@ is true for the stable pointer table.
1257 \item @isSPARK_OBJECT@ is true for spark objects.
1258 \item @isBLOCKED_FETCH@ is true for blocked fetch objects.
1259 \item @isINVALID_INFOTYPE@ is true for all other info types.
1263 The following predicates detect other interesting properties:
1267 \item @isPOINTED@ is true if an object has a pointed type.
1269 If an object is pointed, the following predicates may be true
1270 (otherwise they are false). @isWHNF@ and @isUPDATEABLE@ are
1274 \item @isWHNF@ is true if the object is in Weak Head Normal Form.
1275 Note that unpointed objects are (arbitrarily) not considered to be in WHNF.
1277 @isWHNF@ is true for @PAP@s, @CONSTR@s, @FUN@s and some @BCO@s.
1279 \ToDo{Need to distinguish between whnf BCOs and non-whnf BCOs in their
1282 \item @isBOTTOM@ is true if the object is known to be $\bot$. It is
1283 true of @BH@s. \note{I suspect we'll want to add other kinds of
1284 infotype which are known to be bottom later.}
1286 \item @isUPDATEABLE@ is true if the object may be overwritten with an
1289 @isUPDATEABLE@ is true for @THUNK@s, @AP@s and @BH@s.
1293 It is possible for a pointed object to be neither updatable nor in
1294 WHNF. For example, indirections.
1296 \item @isUNPOINTED@ is true if an object has an unpointed type.
1297 All such objects are boxed since only boxed objects have info pointers.
1299 It is true for @ARR_WORDS@, @ARR_PTRS@, @MUTVAR@, @MUTARR_PTRS@,
1300 @MUTARR_PTRS_FROZEN@, @FOREIGN@ objects, @MVAR@s and @IVAR@s.
1302 \item @isACTIVATION_FRAME@ is true for activation frames of all sorts.
1304 It is true for return addresses and update frames.
1306 \item @isVECTORED_RETADDR@ is true for vectored return addresses.
1307 \item @isDIRECT_RETADDR@ is true for direct return addresses.
1310 \item @isADMINISTRATIVE@ is true for administrative objects:
1311 @TSO@s, the stable pointer table, spark objects and blocked fetches.
1317 \item @isSTATIC@ is true for any statically allocated closure.
1319 \item @isMUTABLE@ is true for objects with mutable pointer fields:
1320 @MUT_ARR@s, @MUTVAR@s, @MVAR@s and @IVAR@s.
1322 \item @isSparkable@ is true if the object can (and should) be sparked.
1323 It is true of updateable objects which are not in WHNF with the
1324 exception of @THUNK_SELECTOR@s and black holes.
1328 As a minor optimisation, we might use the top bits of the @INFO_TYPE@
1329 field to ``cache'' the answers to some of these predicates.
1331 An indirection either points to HNF (post update); or is result of
1332 overwriting a FetchMe, in which case the thing fetched is either
1333 under evaluation (BH), or by now an HNF. Thus, indirections get NoSpark flag.
1338 #define _NF 0x0001 /* Normal form */
1339 #define _NS 0x0002 /* Don't spark */
1340 #define _ST 0x0004 /* Is static */
1341 #define _MU 0x0008 /* Is mutable */
1342 #define _UP 0x0010 /* Is updatable (but not mutable) */
1343 #define _BM 0x0020 /* Is a "primitive" array */
1344 #define _BH 0x0040 /* Is a black hole */
1345 #define _IN 0x0080 /* Is an indirection */
1346 #define _TH 0x0100 /* Is a thunk */
1351 SPEC_N SPEC | _NF | _NS
1353 SPEC_U SPEC | _UP | _TH
1356 GEN_N GEN | _NF | _NS
1358 GEN_U GEN | _UP | _TH
1361 TUPLE _NF | _NS | _BM
1362 DATA _NF | _NS | _BM
1363 MUTUPLE _NF | _NS | _MU | _BM
1364 IMMUTUPLE _NF | _NS | _BM
1376 CAF _NF | _NS | _ST | _IN
1385 STKO_DYNAMIC STKO | _MU
1386 STKO_STATIC STKO | _ST
1388 SPEC_RBH _NS | _MU | _BH
1389 GEN_RBH _NS | _MU | _BH
1397 \subsection{Pointed Objects}
1399 All pointed objects can be entered.
1401 \subsubsection{Function closures}\label{sect:FUN}
1403 Function closures represent lambda abstractions. For example,
1404 consider the top-level declaration:
1406 f = \x -> let g = \y -> x+y
1409 Both @f@ and @g@ are represented by function closures. The closure
1410 for @f@ is {\em static} while that for @g@ is {\em dynamic}.
1412 The layout of a function closure is as follows:
1414 \begin{tabular}{|l|l|l|l|}\hline
1415 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} \\ \hline
1418 The data words (pointers and non-pointers) are the free variables of
1419 the function closure.
1420 The number of pointers
1421 and number of non-pointers are stored in the @INFO_SM@ word, in the least significant
1422 and most significant half-word respectively.
1424 There are several different sorts of function closure, distinguished
1425 by their @INFO_TYPE@ field:
1427 \item @FUN@: a vanilla, dynamically allocated on the heap.
1429 \item $@FUN_@p@_@np$: to speed up garbage collection a number of
1430 specialised forms of @FUN@ are provided, for particular $(p,np)$ pairs,
1431 where $p$ is the number of pointers and $np$ the number of non-pointers.
1433 \item @FUN_STATIC@. Top-level, static, function closures (such as
1434 @f@ above) have a different
1435 layout than dynamic ones:
1437 \begin{tabular}{|l|l|l|}\hline
1438 {\em Fixed header} & {\em Static object link} \\ \hline
1441 Static function closures have no free variables. (However they may refer to other
1442 static closures; these references are recorded in the function closure's SRT.)
1443 They have one field that is not present in dynamic closures, the {\em static object
1444 link} field. This is used by the garbage collector in the same way that to-space
1445 is, to gather closures that have been determined to be live but that have not yet
1447 \note{Static function closures that have no static references, and hence
1448 a null SRT pointer, don't need the static object link field. Is it worth
1449 taking advantage of this? See @CONSTR_STATIC_NOCAF@.}
1452 Each lambda abstraction, $f$, in the STG program has its own private info table.
1453 The following labels are relevant:
1455 \item $f$@_info@ is $f$'s info table.
1456 \item $f$@_entry@ is $f$'s slow entry point (i.e. the entry code of its
1457 info table; so it will label the same byte as $f$@_info@).
1458 \item $f@_fast_@k$ is $f$'s fast entry point. $k$ is the number of arguments
1459 $f$ takes; encoding this number in the fast-entry label occasionally catches some nasty
1460 code-generation errors.
1463 \subsubsection{Data Constructors}\label{sect:CONSTR}
1465 Data-constructor closures represent values constructed with
1466 algebraic data type constructors.
1467 The general layout of data constructors is the same as that for function
1470 \begin{tabular}{|l|l|l|l|}\hline
1471 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} \\ \hline
1475 The SRT pointer in a data constructor's info table is used for the
1476 constructor tag, since a constructor never has any static references.
1478 There are several different sorts of constructor:
1480 \item @CONSTR@: a vanilla, dynamically allocated constructor.
1481 \item @CONSTR_@$p$@_@$np$: just like $@FUN_@p@_@np$.
1482 \item @CONSTR_INTLIKE@.
1483 A dynamically-allocated heap object that looks just like an @Int@. The
1484 garbage collector checks to see if it can common it up with one of a fixed
1485 set of static int-like closures, thus getting it out of the dynamic heap
1488 \item @CONSTR_CHARLIKE@: same deal, but for @Char@.
1490 \item @CONSTR_STATIC@ is similar to @FUN_STATIC@, with the complication that
1491 the layout of the constructor must mimic that of a dynamic constructor,
1492 because a static constructor might be returned to some code that unpacks it.
1493 So its layout is like this:
1495 \begin{tabular}{|l|l|l|l|l|}\hline
1496 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} & {\em Static object link}\\ \hline
1499 The static object link, at the end of the closure, serves the same purpose
1500 as that for @FUN_STATIC@. The pointers in the static constructor can point
1501 only to other static closures.
1503 The static object link occurs last in the closure so that static
1504 constructors can store their data fields in exactly the same place as
1505 dynamic constructors.
1507 \item @CONSTR_STATIC_NOCAF@. A statically allocated data constructor
1508 that guarantees not to point (directly or indirectly) to any CAF
1509 (section~\ref{sect:CAF}). This means it does not need a static object
1510 link field. Since we expect that there might be quite a lot of static
1511 constructors this optimisation makes sense. Furthermore, the @NOCAF@
1512 tag allows the compiler to indicate that no CAFs can be reached
1513 anywhere {\em even indirectly}.
1518 For each data constructor $Con$, two
1519 info tables are generated:
1521 \item $Con$@_info@ labels $Con$'s dynamic info table,
1522 shared by all dynamic instances of the constructor.
1523 \item $Con$@_static@ labels $Con$'s static info table,
1524 shared by all static instances of the constructor.
1527 \subsubsection{Thunks}
1529 \label{sect:THUNK_SEL}
1531 A thunk represents an expression that is not obviously in head normal
1532 form. For example, consider the following top-level definitions:
1534 range = between 1 10
1535 f = \x -> let ys = take x range
1538 Here the right-hand sides of @range@ and @ys@ are both thunks; the former
1539 is static while the latter is dynamic.
1541 The layout of a thunk is the same as that for a function closure,
1542 except that it may have some words of ``slop'' at the end to make sure
1544 at least @MIN_UPD_PAYLOAD@ words in addition to its
1547 \begin{tabular}{|l|l|l|l|l|}\hline
1548 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} & {\em Slop} \\ \hline
1551 The @INFO_SM@ word contains the same information as for function
1552 closures; that is, number of pointers and number of non-pointers (excluding slop).
1554 A thunk differs from a function closure in that it can be updated.
1556 There are several forms of thunk:
1558 \item @THUNK@: a vanilla, dynamically allocated thunk.
1559 The garbage collection code for thunks whose
1560 pointer + non-pointer words is less than @MIN_UPD_PAYLOAD@ differs from
1561 that for function closures and data constructors, because the GC code
1562 has to account for the slop.
1563 \item $@THUNK_@p@_@np$. Similar comments apply.
1564 \item @THUNK_STATIC@. A static thunk is also known as
1565 a {\em constant applicative form}, or {\em CAF}.
1568 \begin{tabular}{|l|l|l|l|l|}\hline
1569 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} & {\em Slop} & {\em Static object link}\\ \hline
1573 \item @THUNK_SELECTOR@ is a (dynamically allocated) thunk
1574 whose entry code performs a simple selection operation from
1575 a data constructor drawn from a single-constructor type. For example,
1578 x = case y of (a,b) -> a
1580 is a selector thunk. A selector thunk is laid out like this:
1582 \begin{tabular}{|l|l|l|l|}\hline
1583 {\em Fixed header} & {\em Selectee pointer} \\ \hline
1586 The @INFO_SM@ word contains the byte offset of the desired word in
1587 the selectee. Note that this is different from all other thunks.
1589 The garbage collector ``peeks'' at the selectee's
1590 tag (in its info table). If it is evaluated, then it goes ahead and do
1591 the selection, and then behaves just as if the selector thunk was an
1592 indirection to the selected field.
1594 evaluated, it treats the selector thunk like any other thunk of that
1595 shape. [Implementation notes.
1596 Copying: only the evacuate routine needs to be special.
1597 Compacting: only the PRStart (marking) routine needs to be special.]
1601 The only label associated with a thunk is its info table:
1603 \item[$f$@_info@] is $f$'s info table.
1607 \subsubsection{Byte-Code Objects}
1610 A Byte-Code Object (BCO) is a container for a a chunk of byte-code,
1611 which can be executed by Hugs. The byte-code represents a
1612 supercombinator in the program: when hugs compiles a module, it
1613 performs lambda lifting and each resulting supercombinator becomes a
1614 byte-code object in the heap.
1616 There are two kinds of BCO: a standard @BCO@ which has an arity of one
1617 or more, and a @BCO_CAF@ which takes no arguments and can be updated.
1618 When a @BCO_CAF@ is updated, the code is thrown away!
1620 The semantics of BCOs are described in Section
1621 \ref{sect:hugs-heap-objects}. A BCO has the following structure:
1624 \begin{tabular}{|l|l|l|l|l|l|}
1626 \emph{Fixed Header} & \emph{Layout} & \emph{Offset} & \emph{Size} &
1627 \emph{Literals} & \emph{Byte code} \\
1634 \item The entry code is a static code fragment/info table that
1635 returns to the scheduler to invoke Hugs (Section
1636 \ref{sect:ghc-to-hugs-switch}).
1637 \item \emph{Layout} contains the number of pointer literals in the
1638 \emph{Literals} field.
1639 \item \emph{Offset} is the offset to the byte code from the start of
1641 \item \emph{Size} is the number of words of byte code in the object.
1642 \item \emph{Literals} contains any pointer and non-pointer literals used in
1643 the byte-codes (including jump addresses), pointers first.
1644 \item \emph{Byte code} contains \emph{Size} words of non-pointer byte
1648 \subsubsection{Partial applications (PAPs)}\label{sect:PAP}
1650 A partial application (PAP) represents a function applied to too few arguments.
1651 It is only built as a result of updating after an argument-satisfaction
1652 check failure. A PAP has the following shape:
1654 \begin{tabular}{|l|l|l|l|}\hline
1655 {\em Fixed header} & {\em No of arg words} & {\em Function closure} & {\em Arg stack} \\ \hline
1658 The ``arg stack'' is a copy of the chunk of stack above the update
1659 frame; ``no of arg words'' tells how many words it consists of. The
1660 function closure is (a pointer to) the closure for the function whose
1661 argument-satisfaction check failed.
1663 There is just one standard form of PAP with @INFO_TYPE@ = @PAP@.
1664 There is just one info table too, called @PAP_info@.
1665 Its entry code simply copies the arg stack chunk back on top of the
1666 stack and enters the function closure. (It has to do a stack overflow test first.)
1668 PAPs are also used to implement Hugs functions (where the arguments are free variables).
1669 PAPs generated by Hugs can be static.
1671 \subsubsection{@AP@ objects}
1674 @AP@ objects are used to represent thunks built by Hugs. The only distintion between
1675 an @AP@ and a @PAP@ is that an @AP@ is updateable.
1678 \begin{tabular}{|l|l|l|l|}
1680 \emph{Fixed Header} & {\em No of arg words} & {\em Function closure} & {\em Arg stack} \\
1685 The entry code pushes an update frame, copies the arg stack chunk on
1686 top of the stack, and enters the function closure. (It has to do a
1687 stack overflow test first.)
1689 The ``arg stack'' is a block of (tagged) arguments representing the
1690 free variables of the thunk; ``no of arg words'' tells how many words
1691 it consists of. The function closure is (a pointer to) the closure
1692 for the thunk. The argument stack may be empty if the thunk has no
1696 \subsubsection{Indirections}
1698 \label{sect:IND_OLDGEN}
1700 Indirection closures just point to other closures. They are introduced
1701 when a thunk is updated to point to its value.
1702 The entry code for all indirections simply enters the closure it points to.
1704 There are several forms of indirection:
1706 \item[@IND@] is the vanilla, dynamically-allocated indirection.
1707 It is removed by the garbage collector. It has the following
1710 \begin{tabular}{|l|l|l|}\hline
1711 {\em Fixed header} & {\em Target closure} \\ \hline
1715 \item[@IND_OLDGEN@] is the indirection used to update an old-generation
1716 thunk. Its shape is like this:
1718 \begin{tabular}{|l|l|l|}\hline
1719 {\em Fixed header} & {\em Mutable link field} & {\em Target closure} \\ \hline
1722 It contains a {\em mutable link field} that is used to string together
1723 all old-generation indirections that might have a pointer into
1727 \item[@IND_PERMANENT@ and @IND_OLDGEN_PERMANENT@.]
1728 for lexical profiling, it is necessary to maintain cost centre
1729 information in an indirection, so ``permanent indirections'' are
1730 retained forever. Otherwise they are just like vanilla indirections.
1731 \note{If a permanent indirection points to another permanent
1732 indirection or a @CONST@ closure, it is possible to elide the indirection
1733 since it will have no effect on the profiler.}
1734 \note{Do we still need @IND@ and @IND_OLDGEN@
1735 in the profiling build, or can we just make
1736 do with one pair whose behaviour changes when profiling is built?}
1738 \item[@IND_STATIC@] is used for overwriting CAFs when they have been
1739 evaluated. Static indirections are not removed by the garbage
1740 collector; and are statically allocated outside the heap (and should
1741 stay there). Their static object link field is used just as for
1742 @FUN_STATIC@ closures.
1745 \begin{tabular}{|l|l|l|}
1747 {\em Fixed header} & {\em Target closure} & {\em Static object link} \\
1754 \subsubsection{Activation Records}
1756 Activation records are parts of the stack described by return address
1757 info tables (closures with @INFO_TYPE@ values of @RET_SMALL@,
1758 @RET_VEC_SMALL@, @RET_BIG@ and @RET_VEC_BIG@). They are described in
1759 section~\ref{sect:activation-records}.
1762 \subsubsection{Black holes, MVars and IVars}
1767 Black hole closures are used to overwrite closures currently being
1768 evaluated. They inform the garbage collector that there are no live
1769 roots in the closure, thus removing a potential space leak.
1771 Black holes also become synchronization points in the threaded world.
1772 They contain a pointer to a list of blocked threads to be awakened
1773 when the black hole is updated (or @NULL@ if the list is empty).
1775 \begin{tabular}{|l|l|l|}
1777 {\em Fixed header} & {\em Mutable link} & {\em Blocked thread link} \\
1781 The {\em Blocked thread link} points to the TSO of the first thread
1782 waiting for the value of this thunk. All subsequent TSOs in the list
1783 are linked together using their @TSO_LINK@ field.
1785 When the blocking queue is non-@NULL@, the black hole must be added to
1786 the mutables list since the TSOs on the list may contain pointers into
1787 the new generation. There is no need to clutter up the mutables list
1788 with black holes with empty blocking queues.
1793 \subsubsection{FetchMes}\label{sect:FETCHME}
1795 In the parallel systems, FetchMes are used to represent pointers into
1796 the global heap. When evaluated, the value they point to is read from
1799 \ToDo{Describe layout}
1801 Because there may be offsets into these arrays, a primitive array
1802 cannot be handled as a FetchMe in the parallel system, but must be
1803 shipped in its entirety if its parent closure is shipped.
1807 \subsection{Unpointed Objects}
1809 A variable of unpointed type is always bound to a {\em value}, never to a {\em thunk}.
1810 For this reason, unpointed objects cannot be entered.
1812 A {\em value} may be:
1814 \item {\em Boxed}, i.e.~represented indirectly by a pointer to a heap object (e.g.~foreign objects, arrays); or
1815 \item {\em Unboxed}, i.e.~represented directly by a bit-pattern in one or more registers (e.g.~@Int#@ and @Float#@).
1817 All {\em pointed} values are {\em boxed}.
1819 \subsubsection{Immutable Objects}
1820 \label{sect:ARR_WORDS1}
1821 \label{sect:ARR_PTRS}
1824 \item[@ARR_WORDS@] is a variable-sized object consisting solely of
1825 non-pointers. It is used for arrays of all
1826 sorts of things (bytes, words, floats, doubles... it doesn't matter).
1828 \begin{tabular}{|c|c|c|c|}
1830 {\em Fixed Hdr} & {\em No of non-pointers} & {\em Non-pointers\ldots} \\ \hline
1834 \item[@ARR_PTRS@] is an immutable, variable sized array of pointers.
1836 \begin{tabular}{|c|c|c|c|}
1838 {\em Fixed Hdr} & {\em Mutable link} & {\em No of pointers} & {\em Pointers\ldots} \\ \hline
1841 The mutable link is present so that we can easily freeze and thaw an
1842 array (by changing the header and adding/removing the array to the
1847 \subsubsection{Mutable Objects}
1848 \label{sect:mutables}
1849 \label{sect:ARR_WORDS2}
1851 \label{sect:MUTARR_PTRS}
1852 \label{sect:MUTARR_PTRS_FROZEN}
1854 Some of these objects are {\em mutable}; they represent objects which
1855 are explicitly mutated by Haskell code through the @ST@ monad.
1856 They're not used for thunks which are updated precisely once.
1857 Depending on the garbage collector, mutable closures may contain extra
1858 header information which allows a generational collector to implement
1859 the ``write barrier.''
1863 \item[@ARR_WORDS@] is also used to represent {\em mutable} arrays of
1864 bytes, words, floats, doubles, etc. It's possible to use the same
1865 object type because even generational collectors don't need to
1868 \item[@MUTVAR@] is a mutable variable.
1870 \begin{tabular}{|c|c|c|}
1872 {\em Fixed Hdr} & {\em Mutable link} & {\em Pointer} \\ \hline
1876 \item[@MUTARR_PTRS@] is a mutable array of pointers.
1877 Such an array may be {\em frozen}, becoming an @SM_MUTARR_PTRS_FROZEN@, with a
1878 different info-table.
1880 \begin{tabular}{|c|c|c|c|}
1882 {\em Fixed Hdr} & {\em Mutable link} & {\em No of ptrs} & {\em Pointers\ldots} \\ \hline
1886 \item[@MUTARR_PTRS_FROZEN@] is a frozen @MUTARR_PTRS@ closure.
1887 The garbage collector converts @MUTARR_PTRS_FROZEN@ to @ARR_PTRS@ as it removes them from
1893 \subsubsection{Foreign Objects}\label{sect:FOREIGN}
1895 Here's what a ForeignObj looks like:
1898 \begin{tabular}{|l|l|l|l|}
1900 {\em Fixed header} & {\em Data} & {\em Free Routine} & {\em Foreign object link} \\
1905 The @FreeRoutine@ is a reference to the finalisation routine to call
1906 when the @ForeignObj@ becomes garbage. If @freeForeignObject@ is
1907 called on a Foreign Object, the @FreeRoutine@ is set to zero and the
1908 garbage collector will not attempt to call @FreeRoutine@ when the
1909 object becomes garbage.
1911 The Foreign object link is a link to the next foreign object in the
1912 list. This list is traversed at the end of garbage collection: if an
1913 object is about to be deallocated (e.g.~it was not marked or
1914 evacuated), the free routine is called and the object is deleted from
1918 The remaining objects types are all administrative --- none of them may be entered.
1920 \subsection{Other weird objects}
1922 \label{sect:BLOCKED_FETCH}
1925 \item[@BlockedFetch@ heap objects (`closures')] (parallel only)
1927 @BlockedFetch@s are inbound fetch messages blocked on local closures.
1928 They arise as entries in a local blocking queue when a fetch has been
1929 received for a local black hole. When awakened, we look at their
1930 contents to figure out where to send a resume.
1932 A @BlockedFetch@ closure has the form:
1934 \begin{tabular}{|l|l|l|l|l|l|}\hline
1935 {\em Fixed header} & link & node & gtid & slot & weight \\ \hline
1939 \item[Spark Closures] (parallel only)
1941 Spark closures are used to link together all closures in the spark pool. When
1942 the current processor is idle, it may choose to speculatively evaluate some of
1943 the closures in the pool. It may also choose to delete sparks from the pool.
1945 \begin{tabular}{|l|l|l|l|l|l|}\hline
1946 {\em Fixed header} & {\em Spark pool link} & {\em Sparked closure} \\ \hline
1950 \item[Slop Objects]\label{sect:slop-objects}
1952 Slop objects are used to overwrite the end of an updatee if it is
1953 larger than an indirection. Normal slop objects consist of an info
1954 pointer a size word and a number of slop words.
1957 \begin{tabular}{|l|l|l|l|l|l|}\hline
1958 {\em Info Pointer} & {\em Size} & {\em Slop Words} \\ \hline
1962 This is too large for single word slop objects which consist of a
1965 Note that slop objects only contain an info pointer, not a standard
1966 fixed header. This doesn't cause problems because slop objects are
1967 always unreachable --- they can only be accessed by linearly scanning
1972 \subsection{Thread State Objects (TSOs)}\label{sect:TSO}
1974 \ToDo{This is very out of date. We now embed a single stack object
1975 within the TSO. TSOs include an ID number which can be used to
1976 generate a hash value. The gransim, profiling and ticky info is
1979 In the multi-threaded system, the state of a suspended thread is
1980 packed up into a Thread State Object (TSO) which contains all the
1981 information needed to restart the thread and for the garbage collector
1982 to find all reachable objects. When a thread is running, it may be
1983 ``unpacked'' into machine registers and various other memory locations
1984 to provide faster access.
1986 Single-threaded systems don't really {\em need\/} TSOs --- but they do
1987 need some way to tell the storage manager about live roots so it is
1988 convenient to use a single TSO to store the mutator state even in
1989 single-threaded systems.
1991 Rather than manage TSOs' alloc/dealloc, etc., in some {\em ad hoc}
1992 way, we instead alloc/dealloc/etc them in the heap; then we can use
1993 all the standard garbage-collection/fetching/flushing/etc machinery on
1994 them. So that's why TSOs are ``heap objects,'' albeit very special
1997 \begin{tabular}{|l|l|}
1998 \hline {\em Fixed header}
1999 \\ \hline @TSO_LINK@
2000 \\ \hline @TSO_WHATNEXT@
2001 \\ \hline @TSO_WHATNEXT_INFO@
2002 \\ \hline @TSO_STACK@
2003 \\ \hline {\em Exception Handlers}
2004 \\ \hline {\em Ticky Info}
2005 \\ \hline {\em Profiling Info}
2006 \\ \hline {\em Parallel Info}
2007 \\ \hline {\em GranSim Info}
2011 The contents of a TSO are:
2014 \item A pointer (@TSO_LINK@) used to maintain a list of threads with a similar
2015 state (e.g.~all runnable, all sleeping, all blocked on the same black
2016 hole, all blocked on the same MVar, etc.)
2018 \item A word (@TSO_WHATNEXT@) which is in suspended threads to record
2019 how to awaken it. This typically requires a program counter which is stored
2020 in the pointer @TSO_WHATNEXT_INFO@
2022 \item A pointer (@TSO_STACK@) to the top stack block.
2024 \item Optional information for ``Ticky Ticky'' statistics: @TSO_STK_HWM@ is
2025 the maximum number of words allocated to this thread.
2027 \item Optional information for profiling:
2028 @TSO_CCC@ is the current cost centre.
2030 \item Optional information for parallel execution:
2033 \item The types of threads (@TSO_TYPE@):
2035 \item[@T_MAIN@] Must be executed locally.
2036 \item[@T_REQUIRED@] A required thread -- may be exported.
2037 \item[@T_ADVISORY@] An advisory thread -- may be exported.
2038 \item[@T_FAIL@] A failure thread -- may be exported.
2041 \item I've no idea what else
2045 \item Optional information for GranSim execution:
2062 \item clock (gransim light only)
2066 Here are the various queues for GrAnSim-type events.
2077 \subsection{Stack Objects}
2078 \label{sect:STACK_OBJECT}
2081 These are ``stack objects,'' which are used in the threaded world as
2082 the stack for each thread is allocated from the heap in smallish
2083 chunks. (The stack in the sequential world is allocated outside of
2086 Each reduction thread has to have its own stack space. As there may
2087 be many such threads, and as any given one may need quite a big stack,
2088 a naive give-'em-a-big-stack-and-let-'em-run approach will cost a {\em
2091 Our approach is to give a thread a small stack space, and then link
2092 on/off extra ``chunks'' as the need arises. Again, this is a
2093 storage-management problem, and, yet again, we choose to graft the
2094 whole business onto the existing heap-management machinery. So stack
2095 objects will live in the heap, be garbage collected, etc., etc..
2097 A stack object is laid out like this:
2100 \begin{tabular}{|l|}
2104 {\em Link to next stack object (0 for last)}
2106 {\em N, the payload size in words}
2108 {\em @Sp@ (byte offset from head of object)}
2110 {\em @Su@ (byte offset from head of object)}
2112 {\em Payload (N words)}
2117 \ToDo{Are stack objects on the mutable list?}
2119 The stack grows downwards, towards decreasing
2120 addresses. This makes it easier to print out the stack
2121 when debugging, and it means that a return address is
2122 at the lowest address of the chunk of stack it ``knows about''
2123 just like an info pointer on a closure.
2125 The garbage collector needs to be able to find all the
2126 pointers in a stack. How does it do this?
2130 \item Within the stack there are return addresses, pushed
2131 by @case@ expressions. Below a return address (i.e. at higher
2132 memory addresses, since the stack grows downwards) is a chunk
2133 of stack that the return address ``knows about'', namely the
2134 activation record of the currently running function.
2136 \item Below each such activation record is a {\em pending-argument
2137 section}, a chunk of
2138 zero or more words that are the arguments to which the result
2139 of the function should be applied. The return address does not
2141 ``know'' how many pending arguments there are, or their types.
2142 (For example, the function might return a result of type $\alpha$.)
2144 \item Below each pending-argument section is another return address,
2145 and so on. Actually, there might be an update frame instead, but we
2146 can consider update frames as a special case of a return address with
2147 a well-defined activation record.
2149 \ToDo{Doesn't it {\em have} to be an update frame? After all, the arg
2150 satisfaction check is @Su - Sp >= ...@.}
2154 The game plan is this. The garbage collector
2155 walks the stack from the top, traversing pending-argument sections and
2156 activation records alternately. Next we discuss how it finds
2157 the pointers in each of these two stack regions.
2160 \subsubsection{Activation records}\label{sect:activation-records}
2162 An {\em activation record} is a contiguous chunk of stack,
2163 with a return address as its first word, followed by as many
2164 data words as the return address ``knows about''. The return
2165 address is actually a fully-fledged info pointer. It points
2166 to an info table, replete with:
2169 \item entry code (i.e. the code to return to).
2170 \item @INFO_TYPE@ is either @RET_SMALL/RET_VEC_SMALL@ or @RET_BIG/RET_VEC_BIG@, depending
2171 on whether the activation record has more than 32 data words (\note{64 for 8-byte-word architectures}) and on whether
2172 to use a direct or a vectored return.
2173 \item @INFO_SM@ for @RET_SMALL@ is a bitmap telling the layout
2174 of the activation record, one bit per word. The least-significant bit
2175 describes the first data word of the record (adjacent to the fixed
2176 header) and so on. A ``@1@'' indicates a non-pointer, a ``@0@''
2178 a pointer. We don't need to indicate exactly how many words there
2180 because when we get to all zeros we can treat the rest of the
2181 activation record as part of the next pending-argument region.
2183 For @RET_BIG@ the @INFO_SM@ field points to a block of bitmap
2184 words, starting with a word that tells how many words are in
2187 \item @INFO_SRT@ is the Static Reference Table for the return
2188 address (Section~\ref{sect:srt}).
2191 The activation record is a fully fledged closure too.
2192 As well as an info pointer, it has all the other attributes of
2193 a fixed header (Section~\ref{sect:fixed-header}) including a saved cost
2194 centre which is reloaded when the return address is entered.
2196 In other words, all the attributes of closures are needed for
2197 activation records, so it's very convenient to make them look alike.
2200 \subsubsection{Pending arguments}
2202 So that the garbage collector can correctly identify pointers
2203 in pending-argument sections we explicitly tag all non-pointers.
2204 Every non-pointer in a pending-argument section is preceded
2205 (at the next lower memory word) by a one-word byte count that
2206 says how many bytes to skip over (excluding the tag word).
2208 The garbage collector traverses a pending argument section from
2209 the top (i.e. lowest memory address). It looks at each word in turn:
2212 \item If it is less than or equal to a small constant @MAX_STACK_TAG@
2214 it treats it as a tag heralding zero or more words of non-pointers,
2215 so it just skips over them.
2217 \item If it points to the code segment, it must be a return
2218 address, so we have come to the end of the pending-argument section.
2220 \item Otherwise it must be a bona fide heap pointer.
2224 \subsection{The Stable Pointer Table}\label{sect:STABLEPTR_TABLE}
2226 A stable pointer is a name for a Haskell object which can be passed to
2227 the external world. It is ``stable'' in the sense that the name does
2228 not change when the Haskell garbage collector runs---in contrast to
2229 the address of the object which may well change.
2231 A stable pointer is represented by an index into the
2232 @StablePointerTable@. The Haskell garbage collector treats the
2233 @StablePointerTable@ as a source of roots for GC.
2235 In order to provide efficient access to stable pointers and to be able
2236 to cope with any number of stable pointers (eg $0 \ldots 100000$), the
2237 table of stable pointers is an array stored on the heap and can grow
2238 when it overflows. (Since we cannot compact the table by moving
2239 stable pointers about, it seems unlikely that a half-empty table can
2240 be reduced in size---this could be fixed if necessary by using a
2241 hash table of some sort.)
2243 In general a stable pointer table closure looks like this:
2246 \begin{tabular}{|l|l|l|l|l|l|l|l|l|l|l|}
2248 {\em Fixed header} & {\em No of pointers} & {\em Free} & $SP_0$ & \ldots & $SP_{n-1}$
2256 \item[@NPtrs@:] number of (stable) pointers.
2258 \item[@Free@:] the byte offset (from the first byte of the object) of the first free stable pointer.
2260 \item[$SP_i$:] A stable pointer slot. If this entry is in use, it is
2261 an ``unstable'' pointer to a closure. If this entry is not in use, it
2262 is a byte offset of the next free stable pointer slot.
2266 When a stable pointer table is evacuated
2268 \item the free list entries are all set to @NULL@ so that the evacuation
2269 code knows they're not pointers;
2271 \item The stable pointer slots are scanned linearly: non-@NULL@ slots
2272 are evacuated and @NULL@-values are chained together to form a new free list.
2275 There's no need to link the stable pointer table onto the mutable
2276 list because we always treat it as a root.
2280 \section{The Bytecode Evaluator}
2282 This section describes how the Hugs interpreter interprets code in the
2283 same environment as compiled code executes. Both evaluation models
2284 use a common garbage collector, so they must agree on the form of
2285 objects in the heap.
2287 Hugs interprets code by converting it to byte-code and applying a
2288 byte-code interpreter to it. Wherever possible, we try to ensure that
2289 the byte-code is all that is required to interpret a section of code.
2290 This means not dynamically generating info tables, and hence we can
2291 only have a small number of possible heap objects each with a statically
2292 compiled info table. Similarly for stack objects: in fact we only
2293 have one Hugs stack object, in which all information is tagged for the
2296 There is, however, one exception to this rule. Hugs must generate
2297 info tables for any constructors it is asked to compile, since the
2298 alternative is to force a context-switch each time compiled code
2299 enters a Hugs-built constructor, which would be prohibitively
2302 We achieve this simplicity by forgoing some of the optimisations used
2307 Whereas compiled code has five different ways of entering a closure
2308 (section~\ref{sect:entering-closures}), interpreted code has only one.
2309 The entry point for interpreted code behaves like slow entry points for
2314 We use just one info table for {\em all\/} direct returns.
2315 This introduces two problems:
2317 \item How does the interpreter know what code to execute?
2319 Instead of pushing just a return address, we push a return BCO and a
2320 trivial return address which just enters the return BCO.
2322 (In a purely interpreted system, we could avoid pushing the trivial
2325 \item How can the garbage collector follow pointers within the
2328 We could push a third word ---a bitmask describing the location of any
2329 pointers within the record--- but, since we're already tagging unboxed
2330 function arguments on the stack, we use the same mechanism for unboxed
2331 values within the activation record.
2333 \ToDo{Do we have to stub out dead variables in the activation frame?}
2339 We trivially support vectored returns by pushing a return vector whose
2340 entries are all the same.
2344 We avoid the need to build SRTs by putting bytecode objects on the
2345 heap and restricting BCOs to a single basic block.
2349 \subsection{Hugs Info Tables}
2351 Hugs requires the following info tables and closures:
2355 Contains both a vectored return table and a direct entry point. All
2356 entry points are the same: they rearrange the stack to match the Hugs
2357 return convention (section~\label{sect:hugs-return-convention}) and return
2358 to the scheduler. When the scheduler restarts the thread, it will
2359 find a BCO on top of the stack and will enter the Hugs interpreter.
2363 This is just the standard info table for an update frame.
2365 \item [Constructors].
2367 The entry code for a constructor jumps to a generic entry point in the
2368 runtime system which decides whether to do a vectored or unvectored
2369 return depending on the shape of the constructor/type. This implies that
2370 info tables must have enough info to make that decision.
2372 \item [@AP@ and @PAP@].
2374 \item [Indirections].
2378 Hugs doesn't generate them itself but it ought to recognise them
2380 \item [Complex primops].
2382 Some of the primops are too complex for GHC to generate inline.
2383 Instead, these primops are hand-written and called as normal functions.
2384 Hugs only needs to know their names and types but doesn't care whether
2385 they are generated by GHC or by hand. Two things to watch:
2389 Hugs must be able to enter these primops even if it is working on a
2390 standalone system that does not support genuine GHC generated code.
2392 \item The complex primops often involve unboxed tuple types (which
2393 Hugs does not support at the source level) so we cannot specify their
2394 types in a Haskell source file.
2400 \subsection{Hugs Heap Objects}
2401 \label{sect:hugs-heap-objects}
2403 \subsubsection{Byte-Code Objects}
2405 Compiled byte code lives on the global heap, in objects called
2406 Byte-Code Objects (or BCOs). The layout of BCOs is described in
2407 detail in Section \ref{sect:BCO}, in this section we will describe
2410 Since byte-code lives on the heap, it can be garbage collected just
2411 like any other heap-resident data. Hugs arranges that any BCO's
2412 referred to by the Hugs symbol tables are treated as live objects by
2413 the garbage collector. When a module is unloaded, the pointers to its
2414 BCOs are removed from the symbol table, and the code will be garbage
2415 collected some time later.
2417 A BCO represents a basic block of code - all entry points are at the
2418 beginning of a BCO, and it is impossible to jump into the middle of
2419 one. A BCO represents not only the code for a function, but also its
2420 closure; a BCO can be entered just like any other closure. Hugs
2421 performs lambda-lifting during compilation to byte-code, and each
2422 top-level combinator becomes a BCO in the heap.
2424 \ToDo{The phrase "all entry points..." suggests that BCOs have multiple
2425 entry points. If so, we need to say a lot more about it...}
2427 \subsubsection{Thunks and partial applications}
2429 A thunk consists of a code pointer, and values for the free variables
2430 of that code. Since Hugs byte-code is lambda-lifted, free variables
2431 become arguments and are expected to be on the stack by the called
2434 Hugs represents updateable thunks with @AP@ objects applying a closure
2435 to a list of arguments. (As for @PAP@s, unboxed arguments should be
2436 preceded by a tag.) When it is entered, it pushes an update frame
2437 followed by its payload on the stack, and enters the first word (which
2438 will be a pointer to a BCO). The layout of @AP@ objects is described
2439 in more detail in Section \ref{sect:AP}.
2441 Partial applications are represented by @PAP@ objects, which are
2444 \ToDo{Hugs Constructors}.
2446 \subsection{Calling conventions}
2447 \label{sect:hugs-calling-conventions}
2448 \label{sect:standard-closures}
2450 The calling convention for any byte-code function is straightforward:
2452 \item Push any arguments on the stack.
2453 \item Push a pointer to the BCO.
2454 \item Begin interpreting the byte code.
2457 In a system containing both GHC and Hugs, the bytecode interpreter
2458 only has to be able to enter BCOs: everything else can be handled by
2459 returning to the compiled world (as described in
2460 Section~\ref{sect:hugs-to-ghc-switch}) and entering the closure
2463 This would work but it would obviously be very inefficient if
2464 we entered a @AP@ by switching worlds, entering the @AP@,
2465 pushing the arguments and function onto the stack, and entering the
2466 function which, likely as not, will be a byte-code object which we
2467 will enter by \emph{returning} to the byte-code interpreter. To avoid
2468 such gratuitious world switching, we choose to recognise certain
2469 closure types as being ``standard'' --- and duplicate the entry code
2470 for the ``standard closures'' in the bytecode interpreter.
2472 A closure is said to be ``standard'' if its entry code is entirely
2473 determined by its info table. \emph{Standard Closures} have the
2474 desirable property that the byte-code interpreter can enter
2475 the closure by simply ``interpreting'' the info table instead of
2476 switching to the compiled world. The standard closures include:
2480 To enter a constructor, we simply return (see Section
2481 \ref{sect:hugs-return-convention}).
2484 To enter an indirection, we simply enter the object it points to
2485 after possibly adjusting the current cost centre.
2489 To enter an @AP@, we push an update frame, push the
2490 arguments, push the function and enter the function.
2491 (Not forgetting a stack check at the start.)
2495 To enter a @PAP@, we push the arguments, push the function and enter
2496 the function. (Not forgetting a stack check at the start.)
2499 To enter a selector, we test whether the selectee is a value. If so,
2500 we simply select the appropriate component; if not, it's simplest to
2501 treat it as a GHC-built closure --- though we could interpret it if we
2506 The most obvious omissions from the above list are @BCO@s (which we
2507 dealt with above) and GHC-built closures (which are covered in Section
2508 \ref{sect:hugs-to-ghc-switch}).
2511 \subsection{Return convention}
2512 \label{sect:hugs-return-convention}
2514 When Hugs pushes a return address, it pushes both a pointer to the BCO
2515 to return to, and a pointer to a static code fragment @HUGS_RET@ (this
2516 is described in Section \ref{sect:ghc-to-hugs-switch}). The
2517 stack layout is shown in Figure \ref{fig:hugs-return-stack}.
2529 %\input{hugs_ret.pstex_t}
2531 \caption{Stack layout for a Hugs return address}
2532 \label{fig:hugs-return-stack}
2543 %\input{hugs_ret2.pstex_t}
2545 \caption{Stack layout on enterings a Hugs return address}
2546 \label{fig:hugs-return2}
2559 %\input{hugs_ret2.pstex_t}
2561 \caption{Stack layout on entering a Hugs return address with an unboxed value}
2562 \label{fig:hugs-return-int}
2575 %\input{hugs_ret3.pstex_t}
2577 \caption{Stack layout on enterings a GHC return address}
2578 \label{fig:hugs-return3}
2592 | restart |--> id_Int#_closure
2595 %\input{hugs_ret2.pstex_t}
2597 \caption{Stack layout on enterings a GHC return address with an unboxed value}
2598 \label{fig:hugs-return-int}
2601 When a Hugs byte-code sequence enters a closure, it examines the
2602 return address on top of the stack.
2606 \item If the return address is @HUGS_RET@, pop the @HUGS_RET@ and the
2607 bco for the continuation off the stack, push a pointer to the constructor onto
2608 the stack and enter the BCO with the current object pointer set to the BCO
2609 (Figure \ref{fig:hugs-return2}).
2611 \item If the top of the stack is not @HUGS_RET@, we need to do a world
2612 switch as described in Section \ref{sect:hugs-to-ghc-switch}.
2616 \ToDo{This duplicates what we say about switching worlds
2617 (section~\ref{sect:switching-worlds}) - kill one or t'other.}
2620 \ToDo{This was in the evaluation model part but it really belongs in
2621 this part which is about the internal details of each of the major
2624 \subsection{Addressing Modes}
2626 To avoid potential alignment problems and simplify garbage collection,
2627 all literal constants are stored in two tables (one boxed, the other
2628 unboxed) within each BCO and are referred to by offsets into the tables.
2629 Slots in the constant tables are word aligned.
2631 \ToDo{How big can the offsets be? Is the offset specified in the
2632 address field or in the instruction?}
2634 Literals can have the following types: char, int, nat, float, double,
2635 and pointer to boxed object. There is no real difference between
2636 char, int, nat and float since they all occupy 32 bits --- but it
2637 costs almost nothing to distinguish them and may improve portability
2638 and simplify debugging.
2640 \subsection{Compilation}
2643 \def\is{\mbox{\it is}}
2644 \def\ts{\mbox{\it ts}}
2645 \def\as{\mbox{\it as}}
2646 \def\bs{\mbox{\it bs}}
2647 \def\cs{\mbox{\it cs}}
2648 \def\rs{\mbox{\it rs}}
2649 \def\us{\mbox{\it us}}
2650 \def\vs{\mbox{\it vs}}
2651 \def\ws{\mbox{\it ws}}
2652 \def\xs{\mbox{\it xs}}
2654 \def\e{\mbox{\it e}}
2655 \def\alts{\mbox{\it alts}}
2656 \def\fail{\mbox{\it fail}}
2657 \def\panic{\mbox{\it panic}}
2658 \def\ua{\mbox{\it ua}}
2659 \def\obj{\mbox{\it obj}}
2660 \def\bco{\mbox{\it bco}}
2661 \def\tag{\mbox{\it tag}}
2662 \def\entry{\mbox{\it entry}}
2663 \def\su{\mbox{\it su}}
2665 \def\Ind#1{{\mbox{\it Ind}\ {#1}}}
2666 \def\update#1{{\mbox{\it update}\ {#1}}}
2668 \def\next{$\Longrightarrow$}
2669 \def\append{\mathrel{+\mkern-6mu+}}
2670 \def\reverse{\mbox{\it reverse}}
2671 \def\size#1{{\vert {#1} \vert}}
2672 \def\arity#1{{\mbox{\it arity}{#1}}}
2674 \def\AP{\mbox{\it AP}}
2675 \def\PAP{\mbox{\it PAP}}
2676 \def\GHCRET{\mbox{\it GHCRET}}
2677 \def\GHCOBJ{\mbox{\it GHCOBJ}}
2679 To make sense of the instructions, we need a sense of how they will be
2680 used. Here is a small compiler for the STG language.
2683 > cg (f{a1, ... am}) = do
2684 > pushAtom am; ... pushAtom a1
2688 > cg (let{x1=rhs1; ... xm=rhsm in e) = do
2689 > ALLOC x1 |rhs1|, ... ALLOC xm |rhsm|
2690 > build x1 rhs1, ... build xm rhsm
2692 > cg (case e of alts) = do
2693 > PUSHALTS (cgAlts alts)
2696 > cgAlts { alt1; ... altm } = cgAlt alt1 $ ... $ cgAlt altm pmFail
2698 > cgAlt (x@C{xs} -> e) fail = do
2700 > HEAPCHECK (heapUse e)
2704 > build x (C{a1, ... am}) = do
2705 > pushUntaggedAtom am; ... pushUntaggedAtom a1
2707 > build x ({v1, ... vm} \ {}. e) = do
2708 > pushVar vm; ... pushVar v1
2709 > PUSHBCO (cgRhs ({v1, ... vm} \ {}. e))
2711 > build x ({v1, ... vm} \ {x1, ... xm}. e) = do
2712 > pushVar vm; ... pushVar v1
2713 > PUSHBCO (cgRhs ({v1, ... vm} \ {x1, ... xm}. e))
2716 > cgRhs (vs \ xs. e) = do
2717 > ARGCHECK (xs ++ vs) -- can be omitted if xs == {}
2718 > STACKCHECK min(stackUse e,heapOverflowSlop)
2719 > HEAPCHECK (heapUse e)
2722 > pushAtom x = pushVar x
2723 > pushAtom i# = PUSHINT i#
2725 > pushVar x = if isGlobalVar x then PUSHGLOBAL x else PUSHLOCAL x
2727 > pushUntaggedAtom x = pushVar x
2728 > pushUntaggedAtom i# = PUSHUNTAGGEDINT i#
2730 > pushVar x = if isGlobalVar x then PUSHGLOBAL x else PUSHLOCAL x
2733 \ToDo{Is there an easy way to add semi-tagging? Would it be that different?}
2735 \ToDo{Optimise thunks of the form @f{x1,...xm}@ so that we build an AP directly}
2737 \subsection{Instructions}
2739 We specify the semantics of instructions using transition rules of
2742 \begin{tabular}{|llrrrrr|}
2744 & $\is$ & $s$ & $\su$ & $h$ & $hp$ & $\sigma$ \\
2745 \next & $\is'$ & $s'$ & $\su'$ & $h'$ & $hp'$ & $\sigma$ \\
2749 where $\is$ is an instruction stream, $s$ is the stack, $\su$ is the
2750 update frame pointer and $h$ is the heap.
2753 \subsection{Stack manipulation}
2757 \item[ Push a global variable ].
2759 \begin{tabular}{|llrrrrr|}
2761 & PUSHGLOBAL $o$ : $\is$ & $s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2762 \next & $\is$ & $\sigma!o:s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2766 \item[ Push a local variable ].
2768 \begin{tabular}{|llrrrrr|}
2770 & PUSHLOCAL $o$ : $\is$ & $s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2771 \next & $\is$ & $s!o : s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2775 \item[ Push an unboxed int ].
2777 \begin{tabular}{|llrrrrr|}
2779 & PUSHINT $o$ : $\is$ & $s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2780 \next & $\is$ & $I\# : \sigma!o : s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2784 The $I\#$ is a tag included for the benefit of the garbage collector.
2785 Similar rules exist for floats, doubles, chars, etc.
2787 \item[ Push an unboxed int ].
2789 \begin{tabular}{|llrrrrr|}
2791 & PUSHUNTAGGEDINT $o$ : $\is$ & $s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2792 \next & $\is$ & $\sigma!o : s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2796 Similar rules exist for floats, doubles, chars, etc.
2798 \item[ Delete environment from stack --- ready for tail call ].
2800 \begin{tabular}{|llrrrrr|}
2802 & SLIDE $m$ $n$ : $\is$ & $\as \append \bs \append \cs$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2803 \next & $\is$ & $\as \append \cs$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2807 where $\size{\as} = m$ and $\size{\bs} = n$.
2810 \item[ Push a return address ].
2812 \begin{tabular}{|llrrrrr|}
2814 & PUSHALTS $o$:$\is$ & $s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2815 \next & $\is$ & $@HUGS_RET@:\sigma!o:s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2819 \item[ Push a BCO ].
2821 \begin{tabular}{|llrrrrr|}
2823 & PUSHBCO $o$ : $\is$ & $s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2824 \next & $\is$ & $\sigma!o : s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2830 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2831 \subsection{Heap manipulation}
2832 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2836 \item[ Allocate a heap object ].
2838 \begin{tabular}{|llrrrrr|}
2840 & ALLOC $m$ : $\is$ & $s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2841 \next & $\is$ & $hp:s$ & $su$ & $h$ & $hp+m$ & $\sigma$ \\
2845 \item[ Build a constructor ].
2847 \begin{tabular}{|llrrrrr|}
2849 & PACK $o$ $o'$ : $\is$ & $\ws \append s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2850 \next & $\is$ & $s$ & $su$ & $h[s!o \mapsto Pack C\{\ws\}]$ & $hp$ & $\sigma$ \\
2854 where $C = \sigma!o'$ and $\size{\ws} = \arity{C}$.
2856 \item[ Build an AP or PAP ].
2858 \begin{tabular}{|llrrrrr|}
2860 & MKAP $o$ $m$:$\is$ & $f : \ws \append s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2861 \next & $\is$ & $s$ & $su$ & $h[s!o \mapsto \AP(f,\ws)]$ & $hp$ & $\sigma$ \\
2865 where $\size{\ws} = m$.
2867 \begin{tabular}{|llrrrrr|}
2869 & MKPAP $o$ $m$:$\is$ & $f : \ws \append s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2870 \next & $\is$ & $s$ & $su$ & $h[s!o \mapsto \PAP(f,\ws)]$ & $hp$ & $\sigma$ \\
2874 where $\size{\ws} = m$.
2876 \item[ Unpacking a constructor ].
2878 \begin{tabular}{|llrrrrr|}
2880 & UNPACK : $is$ & $a : s$ & $su$ & $h[a \mapsto C\ \ws]$ & $hp$ & $\sigma$ \\
2881 \next & $is'$ & $(\reverse\ \ws) \append a : s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2885 The $\reverse\ \ws$ looks expensive but, since the stack grows down
2886 and the heap grows up, that's actually the cheap way of copying from
2887 heap to stack. Looking at the compilation rules, you'll see that we
2888 always push the args in reverse order.
2893 \subsection{Entering a closure}
2897 \item[ Enter a BCO ].
2899 \begin{tabular}{|llrrrrr|}
2901 & [ENTER] & $a : s$ & $su$ & $h[a \mapsto BCO\{\is\} ]$ & $hp$ & $\sigma$ \\
2902 \next & $\is$ & $a : s$ & $su$ & $h$ & $hp$ & $a$ \\
2906 \item[ Enter a PAP closure ].
2908 \begin{tabular}{|llrrrrr|}
2910 & [ENTER] & $a : s$ & $su$ & $h[a \mapsto \PAP(f,\ws)]$ & $hp$ & $\sigma$ \\
2911 \next & [ENTER] & $f : \ws \append s$ & $su$ & $h$ & $hp$ & $???$ \\
2915 \item[ Entering an AP closure ].
2917 \begin{tabular}{|llrrrrr|}
2919 & [ENTER] & $a : s$ & $su$ & $h[a \mapsto \AP(f,ws)]$ & $hp$ & $\sigma$ \\
2920 \next & [ENTER] & $f : \ws \append @UPD_RET@:\su:a:s$ & $su'$ & $h$ & $hp$ & $???$ \\
2926 \item Instead of blindly pushing an update frame for $a$, we can first test whether there's already
2927 an update frame there. If so, overwrite the existing updatee with an indirection to $a$ and
2928 overwrite the updatee field with $a$. (Overwriting $a$ with an indirection to the updatee also
2929 works.) This results in update chains of maximum length 2.
2933 \item[ Returning a constructor ].
2935 \begin{tabular}{|llrrrrr|}
2937 & [ENTER] & $a : @HUGS_RET@ : \alts : s$ & $su$ & $h[a \mapsto C\{\ws\}]$ & $hp$ & $\sigma$ \\
2938 \next & $\alts.\entry$ & $a:s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2943 \item[ Entering an indirection node ].
2945 \begin{tabular}{|llrrrrr|}
2947 & [ENTER] & $a : s$ & $su$ & $h[a \mapsto \Ind{a'}]$ & $hp$ & $\sigma$ \\
2948 \next & [ENTER] & $a' : s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2952 \item[Entering GHC closure].
2954 \begin{tabular}{|llrrrrr|}
2956 & [ENTER] & $a : s$ & $su$ & $h[a \mapsto \GHCOBJ]$ & $hp$ & $\sigma$ \\
2957 \next & [ENTERGHC] & $a : s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2961 \item[Returning a constructor to GHC].
2963 \begin{tabular}{|llrrrrr|}
2965 & [ENTER] & $a : \GHCRET : s$ & $su$ & $h[a \mapsto C \ws]$ & $hp$ & $\sigma$ \\
2966 \next & [ENTERGHC] & $a : \GHCRET : s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2973 \subsection{Updates}
2977 \item[ Updating with a constructor].
2979 \begin{tabular}{|llrrrrr|}
2981 & [ENTER] & $a : @UPD_RET@ : ua : s$ & $su$ & $h[a \mapsto C\{\ws\}]$ & $hp$ & $\sigma$ \\
2982 \next & [ENTER] & $a \append s$ & $su$ & $h[au \mapsto \Ind{a}$ & $hp$ & $\sigma$ \\
2986 \item[ Argument checks].
2988 \begin{tabular}{|llrrrrr|}
2990 & ARGCHECK $m$:$\is$ & $a : \as \append s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
2991 \next & $\is$ & $a : \as \append s$ & $su$ & $h'$ & $hp$ & $\sigma$ \\
2995 where $m \ge (su - sp)$
2997 \begin{tabular}{|llrrrrr|}
2999 & ARGCHECK $m$:$\is$ & $a : \as \append @UPD_RET@:su:ua:s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
3000 \next & $\is$ & $a : \as \append s$ & $su$ & $h'$ & $hp$ & $\sigma$ \\
3004 where $m < (su - sp)$ and
3005 $h' = h[ua \mapsto \Ind{a'}, a' \mapsto \PAP(a,\reverse\ \as) ]$
3007 Again, we reverse the list of values as we transfer them from the
3008 stack to the heap --- reflecting the fact that the stack and heap grow
3009 in different directions.
3013 \subsection{Branches}
3017 \item[ Testing a constructor ].
3019 \begin{tabular}{|llrrrrr|}
3021 & TEST $tag$ $is'$ : $is$ & $a : s$ & $su$ & $h[a \mapsto C\ \ws]$ & $hp$ & $\sigma$ \\
3022 \next & $is$ & $a : s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
3026 where $C.\tag = tag$
3028 \begin{tabular}{|llrrrrr|}
3030 & TEST $tag$ $is'$ : $is$ & $a : s$ & $su$ & $h[a \mapsto C\ \ws]$ & $hp$ & $\sigma$ \\
3031 \next & $is'$ & $a : s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
3035 where $C.\tag \neq tag$
3039 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3040 \subsection{Heap and stack checks}
3041 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3043 \begin{tabular}{|llrrrrr|}
3045 & STACKCHECK $stk$:$\is$ & $s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
3046 \next & $\is$ & $s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
3050 if $s$ has $stk$ free slots.
3052 \begin{tabular}{|llrrrrr|}
3054 & HEAPCHECK $hp$:$\is$ & $s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
3055 \next & $\is$ & $s$ & $su$ & $h$ & $hp$ & $\sigma$ \\
3059 if $h$ has $hp$ free slots.
3061 If either check fails, we push the current bco ($\sigma$) onto the
3062 stack and return to the scheduler. When the scheduler has fixed the
3063 problem, it pops the top object off the stack and reenters it.
3068 \item The bytecode CHECK1000 conservatively checks for 1000 words of heap space and 1000 words of stack space.
3069 We use it to reduce code space and instruction decoding time.
3070 \item The bytecode HEAPCHECK1000 conservatively checks for 1000 words of heap space.
3071 It is used in case alternatives.
3075 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3076 \subsection{Primops}
3077 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3079 \ToDo{primops take m words and return n words. The expect boxed arguments on the stack.}
3082 \section{The Machine Code Evaluator}
3084 This section describes the framework in which compiled code evaluates
3085 expressions. Only at certain points will compiled code need to be
3086 able to talk to the interpreted world; these are discussed in Section
3087 \ref{sect:switching-worlds}.
3089 \subsection{Calling conventions}
3091 \subsubsection{The call/return registers}
3093 One of the problems in designing a virtual machine is that we want it
3094 abstract away from tedious machine details but still reveal enough of
3095 the underlying hardware that we can make sensible decisions about code
3096 generation. A major problem area is the use of registers in
3097 call/return conventions. On a machine with lots of registers, it's
3098 cheaper to pass arguments and results in registers than to pass them
3099 on the stack. On a machine with very few registers, it's cheaper to
3100 pass arguments and results on the stack than to use ``virtual
3101 registers'' in memory. We therefore use a hybrid system: the first
3102 $n$ arguments or results are passed in registers; and the remaining
3103 arguments or results are passed on the stack. For register-poor
3104 architectures, it is important that we allow $n=0$.
3106 We'll label the arguments and results \Arg{1} \ldots \Arg{m} --- with
3107 the understanding that \Arg{1} \ldots \Arg{n} are in registers and
3108 \Arg{n+1} \ldots \Arg{m} are on top of the stack.
3110 Note that the mapping of arguments \Arg{1} \ldots \Arg{n} to machine
3111 registers depends on the {\em kinds} of the arguments. For example,
3112 if the first argument is a Float, we might pass it in a different
3113 register from if it is an Int. In fact, we might find that a given
3114 architecture lets us pass varying numbers of arguments according to
3115 their types. For example, if a CPU has 2 Int registers and 2 Float
3116 registers then we could pass between 2 and 4 arguments in machine
3117 registers --- depending on whether they all have the same kind or they
3118 have different kinds.
3120 \subsubsection{Entering closures}
3121 \label{sect:entering-closures}
3123 To evaluate a closure we jump to the entry code for the closure
3124 passing a pointer to the closure in \Arg{1} so that the entry code can
3125 access its environment.
3127 \subsubsection{Function call}
3129 The function-call mechanism is obviously crucial. There are five different
3133 \item {\em Known combinator (function with no free variables) and enough arguments.}
3135 A fast call can be made: push excess arguments onto stack and jump to
3136 function's {\em fast entry point} passing arguments in \Arg{1} \ldots
3139 The {\em fast entry point} is only called with exactly the right
3140 number of arguments (in \Arg{1} \ldots \Arg{m}) so it can instantly
3141 start doing useful work without first testing whether it has enough
3142 registers or having to pop them off the stack first.
3144 \item {\em Known combinator and insufficient arguments.}
3146 A slow call can be made: push all arguments onto stack and jump to
3147 function's {\em slow entry point}.
3149 Any unpointed arguments which are pushed on the stack must be tagged.
3150 This means pushing an extra word on the stack below the unpointed
3151 words, containing the number of unpointed words above it.
3153 %Todo: forward ref about tagging?
3156 The {\em slow entry point} might be called with insufficient arguments
3157 and so it must test whether there are enough arguments on the stack.
3158 This {\em argument satisfaction check} consists of checking that
3159 @Su-Sp@ is big enough to hold all the arguments (including any tags).
3163 \item If the argument satisfaction check fails, it is because there is
3164 one or more update frames on the stack before the rest of the
3165 arguments that the function needs. In this case, we construct a PAP
3166 (partial application, section~\ref{sect:PAP}) containing the arguments
3167 which are on the stack. The PAP construction code will return to the
3168 update frame with the address of the PAP in \Arg{1}.
3170 \item If the argument satisfaction check succeeds, we jump to the fast
3171 entry point with the arguments in \Arg{1} \ldots \Arg{arity}.
3173 If the fast entry point expects to receive some of \Arg{i} on the
3174 stack, we can reduce the amount of movement required by making the
3175 stack layout for the fast entry point look like the stack layout for
3176 the slow entry point. Since the slow entry point is entered with the
3177 first argument on the top of the stack and with tags in front of any
3178 unpointed arguments, this means that if \Arg{i} is unpointed, there
3179 should be space below it for a tag and that the highest numbered
3180 argument should be passed on the top of the stack.
3182 We usually arrange that the fast entry point is placed immediately
3183 after the slow entry point --- so we can just ``fall through'' to the
3184 fast entry point without performing a jump.
3189 \item {\em Known function closure (function with free variables) and enough arguments.}
3191 A fast call can be made: push excess arguments onto stack and jump to
3192 function's {\em fast entry point} passing a pointer to closure in
3193 \Arg{1} and arguments in \Arg{2} \ldots \Arg{m+1}.
3195 Like the fast entry point for a combinator, the fast entry point for a
3196 closure is only called with appropriate values in \Arg{1} \ldots
3197 \Arg{m+1} so we can start work straight away. The pointer to the
3198 closure is used to access the free variables of the closure.
3201 \item {\em Known function closure and insufficient arguments.}
3203 A slow call can be made: push all arguments onto stack and jump to the
3204 closure's slow entry point passing a pointer to the closure in \Arg{1}.
3206 Again, the slow entry point performs an argument satisfaction check
3207 and either builds a PAP or pops the arguments off the stack into
3208 \Arg{2} \ldots \Arg{m+1} and jumps to the fast entry point.
3211 \item {\em Unknown function closure, thunk or constructor.}
3213 Sometimes, the function being called is not statically identifiable.
3214 Consider, for example, the @compose@ function:
3216 compose f g x = f (g x)
3218 Since @f@ and @g@ are passed as arguments to @compose@, the latter has
3219 to make a heap call. In a heap call the arguments are pushed onto the
3220 stack, and the closure bound to the function is entered. In the
3221 example, a thunk for @(g x)@ will be allocated, (a pointer to it)
3222 pushed on the stack, and the closure bound to @f@ will be
3223 entered. That is, we will jump to @f@s entry point passing @f@ in
3224 \Arg{1}. If \Arg{1} is passed on the stack, it is pushed on top of
3225 the thunk for @(g x)@.
3227 The {\em entry code} for an updateable thunk (which must have arity 0)
3228 pushes an update frame on the stack and starts executing the body of
3229 the closure --- using \Arg{1} to access any free variables. This is
3230 described in more detail in section~\ref{sect:data-updates}.
3232 The {\em entry code} for a non-updateable closure is just the
3233 closure's slow entry point.
3237 In addition to the above considerations, if there are \emph{too many}
3238 arguments then the extra arguments are simply pushed on the stack with
3241 To summarise, a closure's standard (slow) entry point performs the following:
3243 \item[Argument satisfaction check.] (function closure only)
3244 \item[Stack overflow check.]
3245 \item[Heap overflow check.]
3246 \item[Copy free variables out of closure.] %Todo: why?
3247 \item[Eager black holing.] (updateable thunk only) %Todo: forward ref.
3248 \item[Push update frame.]
3249 \item[Evaluate body of closure.]
3253 \subsection{Case expressions and return conventions}
3254 \label{sect:return-conventions}
3256 The {\em evaluation} of a thunk is always initiated by
3257 a @case@ expression. For example:
3259 case x of (a,b) -> E
3262 The code for a @case@ expression looks like this:
3265 \item Push the free variables of the branches on the stack (fv(@E@) in
3267 \item Push a \emph{return address} on the stack.
3268 \item Evaluate the scrutinee (@x@ in this case).
3271 Once evaluation of the scrutinee is complete, execution resumes at the
3272 return address, which points to the code for the expression @E@.
3274 When execution resumes at the return point, there must be some {\em
3275 return convention} that defines where the components of the pair, @a@
3276 and @b@, can be found. The return convention varies according to the
3277 type of the scrutinee @x@:
3283 (A space for) the return address is left on the top of the stack.
3284 Leaving the return address on the stack ensures that the top of the
3285 stack contains a valid activation record
3286 (section~\ref{sect:activation-records}) --- should a garbage collection
3289 \item If @x@ has a boxed type (e.g.~a data constructor or a function),
3290 a pointer to @x@ is returned in \Arg{1}.
3292 \ToDo{Warn that components of E should be extracted as soon as
3293 possible to avoid a space leak.}
3295 \item If @x@ is an unboxed type (e.g.~@Int#@ or @Float#@), @x@ is
3298 \item If @x@ is an unboxed tuple constructor, the components of @x@
3299 are returned in \Arg{1} \ldots \Arg{n} but no object is constructed in
3302 When passing an unboxed tuple to a function, the components are
3303 flattened out and passed in \Arg{1} \ldots \Arg{n} as usual.
3307 \subsection{Vectored Returns}
3309 Many algebraic data types have more than one constructor. For
3310 example, the @Maybe@ type is defined like this:
3312 data Maybe a = Nothing | Just a
3314 How does the return convention encode which of the two constructors is
3315 being returned? A @case@ expression scrutinising a value of @Maybe@
3316 type would look like this:
3322 Rather than pushing a return address before evaluating the scrutinee,
3323 @E@, the @case@ expression pushes (a pointer to) a {\em return
3324 vector}, a static table consisting of two code pointers: one for the
3325 @Just@ alternative, and one for the @Nothing@ alternative.
3331 The constructor @Nothing@ returns by jumping to the first item in the
3332 return vector with a pointer to a (statically built) Nothing closure
3335 It might seem that we could avoid loading \Arg{1} in this case since the
3336 first item in the return vector will know that @Nothing@ was returned
3337 (and can easily access the Nothing closure in the (unlikely) event
3338 that it needs it. The only reason we load \Arg{1} is in case we have to
3339 perform an update (section~\ref{sect:data-updates}).
3343 The constructor @Just@ returns by jumping to the second element of the
3344 return vector with a pointer to the closure in \Arg{1}.
3348 In this way no test need be made to see which constructor returns;
3349 instead, execution resumes immediately in the appropriate branch of
3352 \subsection{Direct Returns}
3354 When a datatype has a large number of constructors, it may be
3355 inappropriate to use vectored returns. The vector tables may be
3356 large and sparse, and it may be better to identify the constructor
3357 using a test-and-branch sequence on the tag. For this reason, we
3358 provide an alternative return convention, called a \emph{direct
3361 In a direct return, the return address pushed on the stack really is a
3362 code pointer. The returning code loads a pointer to the closure being
3363 returned in \Arg{1} as usual, and also loads the tag into \Arg{2}.
3364 The code at the return address will test the tag and jump to the
3365 appropriate code for the case branch.
3367 The choice of whether to use a vectored return or a direct return is
3368 made on a type-by-type basis --- up to a certain maximum number of
3369 constructors imposed by the update mechanism
3370 (section~\ref{sect:data-updates}).
3372 Single-constructor data types also use direct returns, although in
3373 that case there is no need to return a tag in \Arg{2}.
3375 \ToDo{Say whether we pop the return address before returning}
3377 \ToDo{Stack stubbing?}
3379 \subsection{Updates}
3380 \label{sect:data-updates}
3382 The entry code for an updatable thunk (which must be of arity 0):
3385 \item copies the free variables out of the thunk into registers or
3387 \item pushes an {\em update frame} onto the stack.
3389 An update frame is a small activation record consisting of
3391 \begin{tabular}{|l|l|l|}
3393 {\em Fixed header} & {\em Update Frame link} & {\em Updatee} \\
3398 \note{In the semantics part of the STG paper (section 5.6), an update
3399 frame consists of everything down to the last update frame on the
3400 stack. This would make sense too --- and would fit in nicely with
3401 what we're going to do when we add support for speculative
3403 \ToDo{I think update frames contain cost centres sometimes}
3406 If we are doing ``eager blackholing,'' we then overwrite the thunk
3407 with a black hole. Otherwise, we leave it to the garbage collector to
3408 black hole the thunk.
3411 Start evaluating the body of the expression.
3415 When the expression finishes evaluation, it will enter the update
3416 frame on the top of the stack. Since the returner doesn't know
3417 whether it is entering a normal return address/vector or an update
3418 frame, we follow exactly the same conventions as return addresses and
3419 return vectors. That is, on entering the update frame:
3422 \item The value of the thunk is in \Arg{1}. (Recall that only thunks
3423 are updateable and that thunks return just one value.)
3425 \item If the data type is a direct-return type rather than a
3426 vectored-return type, then the tag is in \Arg{2}.
3428 \item The update frame is still on the stack.
3431 We can safely share a single statically-compiled update function
3432 between all types. However, the code must be able to handle both
3433 vectored and direct-return datatypes. This is done by arranging that
3434 the update code looks like this:
3442 |---------------| <- update code pointer
3447 Each entry in the return vector (which is large enough to cover the
3448 largest vectored-return type) points to the update code.
3452 \item overwrites the {\em updatee} with an indirection to \Arg{1};
3453 \item loads @Su@ from the Update Frame link;
3454 \item removes the update frame from the stack; and
3455 \item enters \Arg{1}.
3458 We enter \Arg{1} again, having probably just come from there, because
3459 it knows whether to perform a direct or vectored return. This could
3460 be optimised by compiling special update code for each slot in the
3461 return vector, which performs the correct return.
3463 \subsection{Semi-tagging}
3464 \label{sect:semi-tagging}
3466 When a @case@ expression evaluates a variable that might be bound
3467 to a thunk it is often the case that the scrutinee is already evaluated.
3468 In this case we have paid the penalty of (a) pushing the return address (or
3469 return vector address) on the stack, (b) jumping through the info pointer
3470 of the scrutinee, and (c) returning by an indirect jump through the
3471 return address on the stack.
3473 If we knew that the scrutinee was already evaluated we could generate
3474 (better) code which simply jumps to the appropriate branch of the
3475 @case@ with a pointer to the scrutinee in \Arg{1}. (For direct
3476 returns to multiconstructor datatypes, we might also load the tag into
3479 An obvious idea, therefore, is to test dynamically whether the heap
3480 closure is a value (using the tag in the info table). If not, we
3481 enter the closure as usual; if so, we jump straight to the appropriate
3482 alternative. Here, for example, is pseudo-code for the expression
3483 @(case x of { (a,_,c) -> E }@:
3485 \Arg{1} = <pointer to x>;
3486 tag = \Arg{1}->entry->tag;
3488 Sp--; \\ insert space for return address
3492 goto \Arg{1}->entry;
3494 <info table for return address goes here>
3495 ret: a = \Arg{1}->data1; \\ suck out a and c to avoid space leak
3499 and here is the code for the expression @(case x of { [] -> E1; x:xs -> E2 }@:
3501 \Arg{1} = <pointer to x>;
3502 tag = \Arg{1}->entry->tag;
3504 Sp--; \\ insert space for return address
3508 goto \Arg{1}->entry;
3512 retvec: \\ reversed return vector
3513 <return info table for case goes here>
3515 panic("Direct return into vectored case");
3519 ret2: x = \Arg{1}->head;
3523 There is an obvious cost in compiled code size (but none in the size
3524 of the bytecodes). There is also a cost in execution time if we enter
3525 more thunks than data constructors.
3527 Both the direct and vectored returns are easily modified to chase chains
3528 of indirections too. In the vectored case, this is most easily done by
3529 making sure that @IND = TAG_1 - 1@, and adding an extra field to every
3530 return vector. In the above example, the indirection code would be
3532 ind: \Arg{1} = \Arg{1}->next;
3535 where @ind_loop@ is the second line of code.
3537 Note that we have to leave space for a return address since the return
3538 address expects to find one. If the body of the expression requires a
3539 heap check, we will actually have to write the return address before
3540 entering the garbage collector.
3543 \subsection{Heap and Stack Checks}
3544 \label{sect:heap-and-stack-checks}
3546 The storage manager detects that it needs to garbage collect the old
3547 generation when the evaluator requests a garbage collection without
3548 having moved the heap pointer since the last garbage collection. It
3549 is therefore important that the GC routines {\em not} move the heap
3550 pointer unless the heap check fails. This is different from what
3551 happens in the current STG implementation.
3553 Assuming that the stack can never shrink, we perform a stack check
3554 when we enter a closure but not when we return to a return
3555 continuation. This doesn't work for heap checks because we cannot
3556 predict what will happen to the heap if we call a function.
3558 If we wish to allow the stack to shrink, we need to perform a stack
3559 check whenever we enter a return continuation. Most of these checks
3560 could be eliminated if the storage manager guaranteed that a stack
3561 would always have 1000 words (say) of space after it was shrunk. Then
3562 we can omit stack checks for less than 1000 words in return
3565 When an argument satisfaction check fails, we need to push the closure
3566 (in R1) onto the stack - so we need to perform a stack check. The
3567 problem is that the argument satisfaction check occurs \emph{before}
3568 the stack check. The solution is that the caller of a slow entry
3569 point or closure will guarantee that there is at least one word free
3570 on the stack for the callee to use.
3572 Similarily, if a heap or stack check fails, we need to push the arguments
3573 and closure onto the stack. If we just came from the slow entry point,
3574 there's certainly enough space and it is the responsibility of anyone
3575 using the fast entry point to guarantee that there is enough space.
3577 \ToDo{Be more precise about how much space is required - document it
3578 in the calling convention section.}
3580 \subsection{Handling interrupts/signals}
3583 May have to keep C stack pointer in register to placate OS?
3584 May have to revert black holes - ouch!
3589 \section{The Loader}
3590 \section{The Compilers}
3593 \part{Old stuff - needs to be mined for useful info}
3595 \section{The Scheduler}
3597 The Scheduler is the heart of the run-time system. A running program
3598 consists of a single running thread, and a list of runnable and
3599 blocked threads. The running thread returns to the scheduler when any
3600 of the following conditions arises:
3603 \item A heap check fails, and a garbage collection is required
3604 \item Compiled code needs to switch to interpreted code, and vice
3606 \item The thread becomes blocked.
3607 \item The thread is preempted.
3610 A running system has a global state, consisting of
3613 \item @Hp@, the current heap pointer, which points to the next
3614 available address in the Heap.
3615 \item @HpLim@, the heap limit pointer, which points to the end of the
3617 \item The Thread Preemption Flag, which is set whenever the currently
3618 running thread should be preempted at the next opportunity.
3619 \item A list of runnable threads.
3620 \item A list of blocked threads.
3623 Each thread is represented by a Thread State Object (TSO), which is
3624 described in detail in Section \ref{sect:TSO}.
3626 The following is pseudo-code for the inner loop of the scheduler
3630 while (threads_exist) {
3631 // handle global problems: GC, parallelism, etc
3633 if (external_message) service_message();
3634 // deal with other urgent stuff
3636 pick a runnable thread;
3638 // enter object on top of stack
3639 // if the top object is a BCO, we must enter it
3640 // otherwise appply any heuristic we wish.
3641 if (thread->stack[thread->sp]->info.type == BCO) {
3642 status = runHugs(thread,&smInfo);
3644 status = runGHC(thread,&smInfo);
3646 switch (status) { // handle local problems
3647 case (StackOverflow): enlargeStack; break;
3648 case (Error e) : error(thread,e); break;
3649 case (ExitWith e) : exit(e); break;
3650 case (Yield) : break;
3652 } while (thread_runnable);
3656 \subsection{Invoking the garbage collector}
3657 \subsection{Putting the thread to sleep}
3659 \subsection{Calling C from Haskell}
3661 We distinguish between "safe calls" where the programmer guarantees
3662 that the C function will not call a Haskell function or, in a
3663 multithreaded system, block for a long period of time and "unsafe
3664 calls" where the programmer cannot make that guarantee.
3666 Safe calls are performed without returning to the scheduler and are
3667 discussed elsewhere (\ToDo{discuss elsewhere}).
3669 Unsafe calls are performed by returning an array (outside the Haskell
3670 heap) of arguments and a C function pointer to the scheduler. The
3671 scheduler allocates a new thread from the operating system
3672 (multithreaded system only), spawns a call to the function and
3673 continues executing another thread. When the ccall completes, the
3674 thread informs the scheduler and the scheduler adds the thread to the
3675 runnable threads list.
3677 \ToDo{Describe this in more detail.}
3680 \subsection{Calling Haskell from C}
3682 When C calls a Haskell closure, it sends a message to the scheduler
3683 thread. On receiving the message, the scheduler creates a new Haskell
3684 thread, pushes the arguments to the C function onto the thread's stack
3685 (with tags for unboxed arguments) pushes the Haskell closure and adds
3686 the thread to the runnable list so that it can be entered in the
3689 When the closure returns, the scheduler sends back a message which
3690 awakens the (C) thread.
3692 \ToDo{Do we need to worry about the garbage collector deallocating the
3693 thread if it gets blocked?}
3695 \subsection{Switching Worlds}
3696 \label{sect:switching-worlds}
3698 \ToDo{This has all changed: we always leave a closure on top of the
3699 stack if we mean to continue executing it. The scheduler examines the
3700 top of the stack and tries to guess which world we want to be in. If
3701 it finds a @BCO@, it certainly enters Hugs, if it finds a @GHC@
3702 closure, it certainly enters GHC and if it finds a standard closure,
3703 it is free to choose either one but it's probably best to enter GHC
3704 for everything except @BCO@s and perhaps @AP@s.}
3706 Because this is a combined compiled/interpreted system, the
3707 interpreter will sometimes encounter compiled code, and vice-versa.
3709 All world-switches go via the scheduler, ensuring that the world is in
3710 a known state ready to enter either compiled code or the interpreter.
3711 When a thread is run from the scheduler, the @whatNext@ field in the
3712 TSO (Section \ref{sect:TSO}) is checked to find out how to execute the
3716 \item If @whatNext@ is set to @ReturnGHC@, we load up the required
3717 registers from the TSO and jump to the address at the top of the user
3719 \item If @whatNext@ is set to @EnterGHC@, we load up the required
3720 registers from the TSO and enter the closure pointed to by the top
3722 \item If @whatNext@ is set to @EnterHugs@, we enter the top thing on
3723 the stack, using the interpreter.
3726 There are four cases we need to consider:
3729 \item A GHC thread enters a Hugs-built closure.
3730 \item A GHC thread returns to a Hugs-compiled return address.
3731 \item A Hugs thread enters a GHC-built closure.
3732 \item A Hugs thread returns to a Hugs-compiled return address.
3735 GHC-compiled modules cannot call functions in a Hugs-compiled module
3736 directly, because the compiler has no information about arities in the
3737 external module. Therefore it must assume any top-level objects are
3738 CAFs, and enter their closures.
3740 \ToDo{Hugs-built constructors?}
3742 We now examine the various cases one by one and describe how the
3743 switch happens in each situation.
3745 \subsection{A GHC thread enters a Hugs-built closure}
3746 \label{sect:ghc-to-hugs-switch}
3748 There is three possibilities: GHC has entered a @PAP@, or it has
3749 entered a @AP@, or it has entered the BCO directly (for a top-level
3750 function closure). @AP@s and @PAP@s are ``standard closures'' and
3751 so do not require us to enter the bytecode interpreter.
3753 The entry code for a BCO does the following:
3756 \item Push the address of the object entered on the stack.
3757 \item Save the current state of the thread in its TSO.
3758 \item Return to the scheduler, setting @whatNext@ to @EnterHugs@.
3761 BCO's for thunks and functions have the same entry conventions as
3762 slow entry points: they expect to find their arguments on the stac
3763 with unboxed arguments preceded by appropriate tags.
3765 \subsection{A GHC thread returns to a Hugs-compiled return address}
3766 \label{sect:ghc-to-hugs-switch}
3768 Hugs return addresses are laid out as in Figure
3769 \ref{fig:hugs-return-stack}. If GHC is returning, it will return to
3770 the address at the top of the stack, namely @HUGS_RET@. The code at
3771 @HUGS_RET@ performs the following:
3774 \item pushes \Arg{1} (the return value) on the stack.
3775 \item saves the thread state in the TSO
3776 \item returns to the scheduler with @whatNext@ set to @EnterHugs@.
3779 \noindent When Hugs runs, it will enter the return value, which will
3780 return using the correct Hugs convention (Section
3781 \ref{sect:hugs-return-convention}) to the return address underneath it
3784 \subsection{A Hugs thread enters a GHC-compiled closure}
3785 \label{sect:hugs-to-ghc-switch}
3787 Hugs can recognise a GHC-built closure as not being one of the
3788 following types of object:
3794 \item An indirection, or
3795 \item A constructor.
3798 When Hugs is called on to enter a GHC closure, it executes the
3799 following sequence of instructions:
3802 \item Push the address of the closure on the stack.
3803 \item Save the current state of the thread in the TSO.
3804 \item Return to the scheduler, with the @whatNext@ field set to
3808 \subsection{A Hugs thread returns to a GHC-compiled return address}
3809 \label{sect:hugs-to-ghc-switch}
3811 When Hugs encounters a return address on the stack that is not
3812 @HUGS_RET@, it knows that a world-switch is required. At this point
3813 the stack contains a pointer to the return value, followed by the GHC
3814 return address. The following sequence is then performed:
3817 \item save the state of the thread in the TSO.
3818 \item return to the scheduler, setting @whatNext@ to @EnterGHC@.
3821 The first thing that GHC will do is enter the object on the top of the
3822 stack, which is a pointer to the return value. This value will then
3823 return itself to the return address using the GHC return convention.
3828 \part{Implementation}
3832 This part describes the inner workings of the major components of the system.
3833 Their external interfaces are described in the previous part.
3835 The major components of the system are:
3839 \item The storage manager
3840 \item The machine code evaluator (compiled code)
3841 \item The bytecode evaluator (interpreted code)
3846 \section{Heap objects}
3847 \label{sect:heap-objects}
3848 \label{sect:fixed-header}
3850 \ToDo{Fix this picture}
3860 Every {\em heap object} is a contiguous block
3861 of memory, consisting of a fixed-format {\em header} followed
3862 by zero or more {\em data words}.
3864 \ToDo{I absolutely do not believe that every heap object has a header
3865 like this - ADR. I believe that they all have an info pointer but I
3866 see no readon why stack objects and unpointed heap objects would have
3867 an entry count since this will always be zero.}
3869 The header consists of the following fields:
3871 \item A one-word {\em info pointer}, which points to
3872 the object's static {\em info table}.
3873 \item Zero or more {\em admin words} that support
3875 \item Profiling (notably a {\em cost centre} word).
3876 \note{We could possibly omit the cost centre word from some
3877 administrative objects.}
3878 \item Parallelism (e.g. GranSim keeps the object's global address here,
3879 though GUM keeps a separate hash table).
3880 \item Statistics (e.g. a word to track how many times a thunk is entered.).
3882 We add a Ticky word to the fixed-header part of closures. This is
3883 used to indicate if a closure has been updated but not yet entered. It
3884 is set when the closure is updated and cleared when subsequently
3887 NB: It is {\em not} an ``entry count'', it is an
3888 ``entries-after-update count.'' The commoning up of @CONST@,
3889 @CHARLIKE@ and @INTLIKE@ closures is turned off(?) if this is
3890 required. This has only been done for 2s collection.
3895 Most of the RTS is completely insensitive to the number of admin words.
3896 The total size of the fixed header is @FIXED_HS@.
3898 Many heap objects contain fields allowing them to be inserted onto lists
3899 during evaluation or during garbage collection. The lists required by
3900 the evaluator and storage manager are as follows.
3903 \item 2 lists of threads: runnable threads and sleeping threads.
3905 \item The {\em static object list} is a list of all statically
3906 allocated objects which might contain pointers into the heap.
3907 (Section~\ref{sect:static-objects}.)
3909 \item The {\em updated thunk list} is a list of all thunks in the old
3910 generation which have been updated with an indirection.
3911 (Section~\ref{sect:IND_OLDGEN}.)
3913 \item The {\em mutables list} is a list of all other objects in the
3914 old generation which might contain pointers into the new generation.
3915 Most of the object on this list are ``mutable.''
3916 (Section~\ref{sect:mutables}.)
3918 \item The {\em Foreign Object list} is a list of all foreign objects
3919 which have not yet been deallocated. (Section~\ref{sect:FOREIGN}.)
3921 \item The {\em Spark pool} is a doubly(?) linked list of Spark objects
3922 maintained by the parallel system. (Section~\ref{sect:SPARK}.)
3924 \item The {\em Blocked Fetch list} (or
3925 lists?). (Section~\ref{sect:BLOCKED_FETCH}.)
3927 \item For each thread, there is a list of all update frames on the
3928 stack. (Section~\ref{sect:data-updates}.)
3933 \ToDo{The links for these fields are usually inserted immediately
3934 after the fixed header except ...}
3936 \subsection{Info Tables}
3938 An {\em info table} is a contiguous block of memory, {\em laid out
3939 backwards}. That is, the first field in the list that follows
3940 occupies the highest memory address, and the successive fields occupy
3941 successive decreasing memory addresses.
3944 \begin{tabular}{|c|}
3945 \hline Parallelism Info
3946 \\ \hline Profile Info
3947 \\ \hline Debug Info
3948 \\ \hline Tag / Static reference table
3949 \\ \hline Storage manager layout info
3950 \\ \hline Closure type
3951 \\ \hline entry code
3955 An info table has the following contents (working backwards in memory
3958 \item The {\em entry code} for the closure.
3959 This code appears literally as the (large) last entry in the
3960 info table, immediately preceded by the rest of the info table.
3961 An {\em info pointer} always points to the first byte of the entry code.
3963 \item A one-word {\em closure type field}, @INFO_TYPE@, identifies what kind
3964 of closure the object is. The various types of closure are described
3965 in Section~\ref{sect:closures}.
3966 In some configurations, some useful properties of
3967 closures (is it a HNF? can it be sparked?)
3968 are represented as high-order bits so they can be tested quickly.
3970 \item A single pointer or word --- the {\em storage manager info field},
3971 @INFO_SM@, contains auxiliary information describing the closure's
3972 precise layout, for the benefit of the garbage collector and the code
3973 that stuffs graph into packets for transmission over the network.
3975 \item A one-word {\em Tag/Static Reference Table} field, @INFO_SRT@.
3976 For data constructors, this field contains the constructor tag, in the
3977 range $0..n-1$ where $n$ is the number of constructors. For all other
3978 objects it contains a pointer to a table which enables the garbage
3979 collector to identify all accessible code and CAFs. They are fully
3980 described in Section~\ref{sect:srt}.
3982 \item {\em Profiling info\/}
3984 Closure category records are attached to the info table of the
3985 closure. They are declared with the info table. We put pointers to
3986 these ClCat things in info tables. We need these ClCat things because
3987 they are mutable, whereas info tables are immutable. Hashing will map
3988 similar categories to the same hash value allowing statistics to be
3989 grouped by closure category.
3991 Cost Centres and Closure Categories are hashed to provide indexes
3992 against which arbitrary information can be stored. These indexes are
3993 memoised in the appropriate cost centre or category record and
3994 subsequent hashes avoided by the index routine (it simply returns the
3997 There are different features which can be hashed allowing information
3998 to be stored for different groupings. Cost centres have the cost
3999 centre recorded (using the pointer), module and group. Closure
4000 categories have the closure description and the type
4001 description. Records with the same feature will be hashed to the same
4004 The initialisation routines, @init_index_<feature>@, allocate a hash
4005 table in which the cost centre / category records are stored. The
4006 lower bound for the table size is taken from @max_<feature>_no@. They
4007 return the actual table size used (the next power of 2). Unused
4008 locations in the hash table are indicated by a 0 entry. Successive
4009 @init_index_<feature>@ calls just return the actual table size.
4011 Calls to @index_<feature>@ will insert the cost centre / category
4012 record in the @<feature>@ hash table, if not already inserted. The hash
4013 index is memoised in the record and returned.
4015 CURRENTLY ONLY ONE MEMOISATION SLOT IS AVILABLE IN EACH RECORD SO
4016 HASHING CAN ONLY BE DONE ON ONE FEATURE FOR EACH RECORD. This can be
4017 easily relaxed at the expense of extra memoisation space or continued
4020 The initialisation routines must be called before initialisation of
4021 the stacks and heap as they require to allocate storage. It is also
4022 expected that the caller may want to allocate additional storage in
4023 which to store profiling information based on the return table size
4027 \begin{tabular}{|l|}
4031 \\ \hline Description String
4032 \\ \hline Type String
4038 \item[Hash Index] Memoised copy
4040 Is this category selected (-1 == not memoised, selected? 0 or 1)
4042 One of the following values (defined in CostCentre.lh):
4050 A partial application.
4052 A thunk, or suspension.
4057 \item[@ForeignObj_K@]
4058 A Foreign object (non-Haskell heap resident).
4060 The Stable Pointer table. (There should only be one of these but it
4061 represents a form of weak space leak since it can't shrink to meet
4062 non-demand so it may be worth watching separately? ADR)
4063 \item[@INTERNAL_KIND@]
4064 Something internal to the runtime system.
4068 \item[Description] Source derived string detailing closure description.
4069 \item[Type] Source derived string detailing closure type.
4072 \item {\em Parallelism info\/}
4075 \item {\em Debugging info\/}
4081 %-----------------------------------------------------------------------------
4082 \subsection{Kinds of Heap Object}
4083 \label{sect:closures}
4085 Heap objects can be classified in several ways, but one useful one is
4089 {\em Static closures} occupy fixed, statically-allocated memory
4090 locations, with globally known addresses.
4093 {\em Dynamic closures} are individually allocated in the heap.
4096 {\em Stack closures} are closures allocated within a thread's stack
4097 (which is itself a heap object). Unlike other closures, there are
4098 never any pointers to stack closures. Stack closures are discussed in
4099 Section~\ref{sect:stacks}.
4102 A second useful classification is this:
4105 {\em Executive objects}, such as thunks and data constructors,
4106 participate directly in a program's execution. They can be subdivided into
4107 three kinds of objects according to their type:
4110 {\em Pointed objects}, represent values of a {\em pointed} type
4111 (<.pointed types launchbury.>) --i.e.~a type that includes $\bottom$ such as @Int@ or @Int# -> Int#@.
4113 \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#@.
4115 \item {\em Activation frames}, represent ``continuations''. They are
4116 always stored on the stack and are never pointed to by heap objects or
4117 passed as arguments. \note{It's not clear if this will still be true
4118 once we support speculative evaluation.}
4122 \item {\em Administrative objects}, such as stack objects and thread
4123 state objects, do not represent values in the original program.
4126 Only pointed objects can be entered. All pointed objects share a
4127 common header format: the ``pointed header''; while all unpointed
4128 objects share a common header format: the ``unpointed header''.
4129 \ToDo{Describe the difference and update the diagrams to mention
4130 an appropriate header type.}
4132 This section enumerates all the kinds of heap objects in the system.
4133 Each is identified by a distinct @INFO_TYPE@ tag in its info table.
4135 \ToDo{Check this table very carefully}
4137 \begin{tabular}{|l|l|l|l|l|l|l|l|l|l|l|}
4140 closure kind & HNF & UPD & NS & STA & THU & MUT & UPT & BH & IND & Section \\
4146 @CONSTR@ & 1 & & 1 & & & & & & & \ref{sect:CONSTR} \\
4147 @CONSTR_STATIC@ & 1 & & 1 & 1 & & & & & & \ref{sect:CONSTR} \\
4148 @CONSTR_STATIC_NOCAF@ & 1 & & 1 & 1 & & & & & & \ref{sect:CONSTR} \\
4150 @FUN@ & 1 & & ? & & & & & & & \ref{sect:FUN} \\
4151 @FUN_STATIC@ & 1 & & ? & 1 & & & & & & \ref{sect:FUN} \\
4153 @THUNK@ & & 1 & & & 1 & & & & & \ref{sect:THUNK} \\
4154 @THUNK_STATIC@ & & 1 & & 1 & 1 & & & & & \ref{sect:THUNK} \\
4155 @THUNK_SELECTOR@ & & 1 & 1 & & 1 & & & & & \ref{sect:THUNK_SEL} \\
4157 @BCO@ & 1 & & 1 & & & & & & & \ref{sect:BCO} \\
4158 @BCO_CAF@ & & 1 & & & 1 & & & & & \ref{sect:BCO} \\
4160 @AP@ & & 1 & & & 1 & & & & & \ref{sect:AP} \\
4161 @PAP@ & 1 & & 1 & & & & & & & \ref{sect:PAP} \\
4163 @IND@ & ? & & ? & & ? & & & & 1 & \ref{sect:IND} \\
4164 @IND_OLDGEN@ & ? & & ? & & ? & & & & 1 & \ref{sect:IND} \\
4165 @IND_PERM@ & ? & & ? & & ? & & & & 1 & \ref{sect:IND} \\
4166 @IND_OLDGEN_PERM@ & ? & & ? & & ? & & & & 1 & \ref{sect:IND} \\
4167 @IND_STATIC@ & ? & & ? & 1 & ? & & & & 1 & \ref{sect:IND} \\
4174 @ARR_WORDS@ & 1 & & 1 & & & & 1 & & & \ref{sect:ARR_WORDS1},\ref{sect:ARR_WORDS2} \\
4175 @ARR_PTRS@ & 1 & & 1 & & & & 1 & & & \ref{sect:ARR_PTRS} \\
4176 @MUTVAR@ & 1 & & 1 & & & 1 & 1 & & & \ref{sect:MUTVAR} \\
4177 @MUTARR_PTRS@ & 1 & & 1 & & & 1 & 1 & & & \ref{sect:MUTARR_PTRS} \\
4178 @MUTARR_PTRS_FROZEN@ & 1 & & 1 & & & 1 & 1 & & & \ref{sect:MUTARR_PTRS_FROZEN} \\
4180 @FOREIGN@ & 1 & & 1 & & & & 1 & & & \ref{sect:FOREIGN} \\
4182 @BH@ & & 1 & 1 & & ? & ? & & 1 & ? & \ref{sect:BH} \\
4183 @MVAR@ & 1 & & 1 & & & & & & & \ref{sect:MVAR} \\
4184 @IVAR@ & 1 & & 1 & & & & & & & \ref{sect:IVAR} \\
4185 @FETCHME@ & 1 & & 1 & & & & & & & \ref{sect:FETCHME} \\
4189 Activation frames do not live (directly) on the heap --- but they have
4190 a similar organisation. The classification bits are all zero in
4193 \begin{tabular}{|l|l|}\hline
4194 closure kind & Section \\ \hline
4195 @RET_SMALL@ & \ref{sect:activation-records} \\
4196 @RET_VEC_SMALL@ & \ref{sect:activation-records} \\
4197 @RET_BIG@ & \ref{sect:activation-records} \\
4198 @RET_VEC_BIG@ & \ref{sect:activation-records} \\
4199 @UPDATE_FRAME@ & \ref{sect:activation-records} \\
4203 There are also a number of administrative objects. The classification bits are
4204 all zero in administrative objects.
4206 \begin{tabular}{|l|l|}\hline
4207 closure kind & Section \\ \hline
4208 @TSO@ & \ref{sect:TSO} \\
4209 @STACK_OBJECT@ & \ref{sect:STACK_OBJECT} \\
4210 @STABLEPTR_TABLE@ & \ref{sect:STABLEPTR_TABLE} \\
4211 @SPARK_OBJECT@ & \ref{sect:SPARK} \\
4212 @BLOCKED_FETCH@ & \ref{sect:BLOCKED_FETCH} \\
4216 \ToDo{I guess the parallel system has something like a stable ptr
4217 table. Is there any opportunity for sharing code/data structures
4221 \subsection{Classification bits}
4223 The top bits of the @INFO_TYPE@ tag tells what sort of animal the
4226 \begin{tabular}{|l|l|l|} \hline
4227 Abbrev & Bit & Interpretation \\ \hline
4228 HNF & 0 & 1 $\Rightarrow$ Head normal form \\
4229 UPD & 4 & 1 $\Rightarrow$ May be updated (inconsistent with being a HNF) \\
4230 NS & 1 & 1 $\Rightarrow$ Don't spark me (Any HNF will have this set to 1)\\
4231 STA & 2 & 1 $\Rightarrow$ This is a static closure \\
4232 THU & 8 & 1 $\Rightarrow$ Is a thunk \\
4233 MUT & 3 & 1 $\Rightarrow$ Has mutable pointer fields \\
4234 UPT & 5 & 1 $\Rightarrow$ Has an unpointed type (eg a primitive array) \\
4235 BH & 6 & 1 $\Rightarrow$ Is a black hole \\
4236 IND & 7 & 1 $\Rightarrow$ Is an indirection \\
4240 Updatable structures (@_UP@) are thunks that may be shared. Primitive
4241 arrays (@_BM@ -- Big Mothers) are structures that are always held
4242 in-memory (basically extensions of a closure). Because there may be
4243 offsets into these arrays, a primitive array cannot be handled as a
4244 FetchMe in the parallel system, but must be shipped in its entirety if
4245 its parent closure is shipped.
4247 The other bits in the info-type field simply give a unique bit-pattern
4248 to identify the closure type.
4252 #define _NF 0x0001 /* Normal form */
4253 #define _NS 0x0002 /* Don't spark */
4254 #define _ST 0x0004 /* Is static */
4255 #define _MU 0x0008 /* Is mutable */
4256 #define _UP 0x0010 /* Is updatable (but not mutable) */
4257 #define _BM 0x0020 /* Is a "primitive" array */
4258 #define _BH 0x0040 /* Is a black hole */
4259 #define _IN 0x0080 /* Is an indirection */
4260 #define _TH 0x0100 /* Is a thunk */
4265 SPEC_N SPEC | _NF | _NS
4267 SPEC_U SPEC | _UP | _TH
4270 GEN_N GEN | _NF | _NS
4272 GEN_U GEN | _UP | _TH
4275 TUPLE _NF | _NS | _BM
4276 DATA _NF | _NS | _BM
4277 MUTUPLE _NF | _NS | _MU | _BM
4278 IMMUTUPLE _NF | _NS | _BM
4290 CAF _NF | _NS | _ST | _IN
4299 STKO_DYNAMIC STKO | _MU
4300 STKO_STATIC STKO | _ST
4302 SPEC_RBH _NS | _MU | _BH
4303 GEN_RBH _NS | _MU | _BH
4312 An indirection either points to HNF (post update); or is result of
4313 overwriting a FetchMe, in which case the thing fetched is either
4314 under evaluation (BH), or by now an HNF. Thus, indirections get NoSpark flag.
4318 \subsection{Hugs Objects}
4320 \subsubsection{Byte-Code Objects}
4323 A Byte-Code Object (BCO) is a container for a a chunk of byte-code,
4324 which can be executed by Hugs. The byte-code represents a
4325 supercombinator in the program: when hugs compiles a module, it
4326 performs lambda lifting and each resulting supercombinator becomes a
4327 byte-code object in the heap.
4329 There are two kinds of BCO: a standard @BCO@ which has an arity of one
4330 or more, and a @BCO_CAF@ which takes no arguments and can be updated.
4331 When a @BCO_CAF@ is updated, the code is thrown away!
4333 The semantics of BCOs are described in Section
4334 \ref{sect:hugs-heap-objects}. A BCO has the following structure:
4337 \begin{tabular}{|l|l|l|l|l|l|}
4339 \emph{Fixed Header} & \emph{Layout} & \emph{Offset} & \emph{Size} &
4340 \emph{Literals} & \emph{Byte code} \\
4347 \item The entry code is a static code fragment/info table that
4348 returns to the scheduler to invoke Hugs (Section
4349 \ref{sect:ghc-to-hugs-switch}).
4350 \item \emph{Layout} contains the number of pointer literals in the
4351 \emph{Literals} field.
4352 \item \emph{Offset} is the offset to the byte code from the start of
4354 \item \emph{Size} is the number of words of byte code in the object.
4355 \item \emph{Literals} contains any pointer and non-pointer literals used in
4356 the byte-codes (including jump addresses), pointers first.
4357 \item \emph{Byte code} contains \emph{Size} words of non-pointer byte
4361 \subsection{Pointed Objects}
4363 All pointed objects can be entered.
4365 \subsubsection{Function closures}\label{sect:FUN}
4367 Function closures represent lambda abstractions. For example,
4368 consider the top-level declaration:
4370 f = \x -> let g = \y -> x+y
4373 Both @f@ and @g@ are represented by function closures. The closure
4374 for @f@ is {\em static} while that for @g@ is {\em dynamic}.
4376 The layout of a function closure is as follows:
4378 \begin{tabular}{|l|l|l|l|}\hline
4379 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} \\ \hline
4382 The data words (pointers and non-pointers) are the free variables of
4383 the function closure.
4384 The number of pointers
4385 and number of non-pointers are stored in the @INFO_SM@ word, in the least significant
4386 and most significant half-word respectively.
4388 There are several different sorts of function closure, distinguished
4389 by their @INFO_TYPE@ field:
4391 \item @FUN@: a vanilla, dynamically allocated on the heap.
4393 \item $@FUN_@p@_@np$: to speed up garbage collection a number of
4394 specialised forms of @FUN@ are provided, for particular $(p,np)$ pairs,
4395 where $p$ is the number of pointers and $np$ the number of non-pointers.
4397 \item @FUN_STATIC@. Top-level, static, function closures (such as
4398 @f@ above) have a different
4399 layout than dynamic ones:
4401 \begin{tabular}{|l|l|l|}\hline
4402 {\em Fixed header} & {\em Static object link} \\ \hline
4405 Static function closures have no free variables. (However they may refer to other
4406 static closures; these references are recorded in the function closure's SRT.)
4407 They have one field that is not present in dynamic closures, the {\em static object
4408 link} field. This is used by the garbage collector in the same way that to-space
4409 is, to gather closures that have been determined to be live but that have not yet
4411 \note{Static function closures that have no static references, and hence
4412 a null SRT pointer, don't need the static object link field. Is it worth
4413 taking advantage of this? See @CONSTR_STATIC_NOCAF@.}
4416 Each lambda abstraction, $f$, in the STG program has its own private info table.
4417 The following labels are relevant:
4419 \item $f$@_info@ is $f$'s info table.
4420 \item $f$@_entry@ is $f$'s slow entry point (i.e. the entry code of its
4421 info table; so it will label the same byte as $f$@_info@).
4422 \item $f@_fast_@k$ is $f$'s fast entry point. $k$ is the number of arguments
4423 $f$ takes; encoding this number in the fast-entry label occasionally catches some nasty
4424 code-generation errors.
4427 \subsubsection{Data Constructors}\label{sect:CONSTR}
4429 Data-constructor closures represent values constructed with
4430 algebraic data type constructors.
4431 The general layout of data constructors is the same as that for function
4434 \begin{tabular}{|l|l|l|l|}\hline
4435 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} \\ \hline
4439 The SRT pointer in a data constructor's info table is used for the
4440 constructor tag, since a constructor never has any static references.
4442 There are several different sorts of constructor:
4444 \item @CONSTR@: a vanilla, dynamically allocated constructor.
4445 \item @CONSTR_@$p$@_@$np$: just like $@FUN_@p@_@np$.
4446 \item @CONSTR_INTLIKE@.
4447 A dynamically-allocated heap object that looks just like an @Int@. The
4448 garbage collector checks to see if it can common it up with one of a fixed
4449 set of static int-like closures, thus getting it out of the dynamic heap
4452 \item @CONSTR_CHARLIKE@: same deal, but for @Char@.
4454 \item @CONSTR_STATIC@ is similar to @FUN_STATIC@, with the complication that
4455 the layout of the constructor must mimic that of a dynamic constructor,
4456 because a static constructor might be returned to some code that unpacks it.
4457 So its layout is like this:
4459 \begin{tabular}{|l|l|l|l|l|}\hline
4460 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} & {\em Static object link}\\ \hline
4463 The static object link, at the end of the closure, serves the same purpose
4464 as that for @FUN_STATIC@. The pointers in the static constructor can point
4465 only to other static closures.
4467 The static object link occurs last in the closure so that static
4468 constructors can store their data fields in exactly the same place as
4469 dynamic constructors.
4471 \item @CONSTR_STATIC_NOCAF@. A statically allocated data constructor
4472 that guarantees not to point (directly or indirectly) to any CAF
4473 (section~\ref{sect:CAF}). This means it does not need a static object
4474 link field. Since we expect that there might be quite a lot of static
4475 constructors this optimisation makes sense. Furthermore, the @NOCAF@
4476 tag allows the compiler to indicate that no CAFs can be reached
4477 anywhere {\em even indirectly}.
4482 For each data constructor $Con$, two
4483 info tables are generated:
4485 \item $Con$@_info@ labels $Con$'s dynamic info table,
4486 shared by all dynamic instances of the constructor.
4487 \item $Con$@_static@ labels $Con$'s static info table,
4488 shared by all static instances of the constructor.
4491 \subsubsection{Thunks}
4493 \label{sect:THUNK_SEL}
4495 A thunk represents an expression that is not obviously in head normal
4496 form. For example, consider the following top-level definitions:
4498 range = between 1 10
4499 f = \x -> let ys = take x range
4502 Here the right-hand sides of @range@ and @ys@ are both thunks; the former
4503 is static while the latter is dynamic.
4505 The layout of a thunk is the same as that for a function closure,
4506 except that it may have some words of ``slop'' at the end to make sure
4508 at least @MIN_UPD_PAYLOAD@ words in addition to its
4511 \begin{tabular}{|l|l|l|l|l|}\hline
4512 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} & {\em Slop} \\ \hline
4515 The @INFO_SM@ word contains the same information as for function
4516 closures; that is, number of pointers and number of non-pointers (excluding slop).
4518 A thunk differs from a function closure in that it can be updated.
4520 There are several forms of thunk:
4522 \item @THUNK@: a vanilla, dynamically allocated thunk.
4523 The garbage collection code for thunks whose
4524 pointer + non-pointer words is less than @MIN_UPD_PAYLOAD@ differs from
4525 that for function closures and data constructors, because the GC code
4526 has to account for the slop.
4527 \item $@THUNK_@p@_@np$. Similar comments apply.
4528 \item @THUNK_STATIC@. A static thunk is also known as
4529 a {\em constant applicative form}, or {\em CAF}.
4532 \begin{tabular}{|l|l|l|l|l|}\hline
4533 {\em Fixed header} & {\em Pointers} & {\em Non-pointers} & {\em Slop} & {\em Static object link}\\ \hline
4537 \item @THUNK_SELECTOR@ is a (dynamically allocated) thunk
4538 whose entry code performs a simple selection operation from
4539 a data constructor drawn from a single-constructor type. For example,
4542 x = case y of (a,b) -> a
4544 is a selector thunk. A selector thunk is laid out like this:
4546 \begin{tabular}{|l|l|l|l|}\hline
4547 {\em Fixed header} & {\em Selectee pointer} \\ \hline
4550 The @INFO_SM@ word contains the byte offset of the desired word in
4551 the selectee. Note that this is different from all other thunks.
4553 The garbage collector ``peeks'' at the selectee's
4554 tag (in its info table). If it is evaluated, then it goes ahead and do
4555 the selection, and then behaves just as if the selector thunk was an
4556 indirection to the selected field.
4558 evaluated, it treats the selector thunk like any other thunk of that
4559 shape. [Implementation notes.
4560 Copying: only the evacuate routine needs to be special.
4561 Compacting: only the PRStart (marking) routine needs to be special.]
4565 The only label associated with a thunk is its info table:
4567 \item[$f$@_info@] is $f$'s info table.
4571 \subsubsection{Partial applications (PAPs)}\label{sect:PAP}
4573 A partial application (PAP) represents a function applied to too few arguments.
4574 It is only built as a result of updating after an argument-satisfaction
4575 check failure. A PAP has the following shape:
4577 \begin{tabular}{|l|l|l|l|}\hline
4578 {\em Fixed header} & {\em No of arg words} & {\em Function closure} & {\em Arg stack} \\ \hline
4581 The ``arg stack'' is a copy of the chunk of stack above the update
4582 frame; ``no of arg words'' tells how many words it consists of. The
4583 function closure is (a pointer to) the closure for the function whose
4584 argument-satisfaction check failed.
4586 There is just one standard form of PAP with @INFO_TYPE@ = @PAP@.
4587 There is just one info table too, called @PAP_info@.
4588 Its entry code simply copies the arg stack chunk back on top of the
4589 stack and enters the function closure. (It has to do a stack overflow test first.)
4591 PAPs are also used to implement Hugs functions (where the arguments are free variables).
4592 PAPs generated by Hugs can be static.
4594 \subsubsection{@AP@ objects}
4597 @AP@ objects are used to represent thunks built by Hugs. The only distintion between
4598 an @AP@ and a @PAP@ is that an @AP@ is updateable.
4601 \begin{tabular}{|l|l|l|l|}
4603 \emph{Fixed Header} & {\em No of arg words} & {\em Function closure} & {\em Arg stack} \\
4608 The entry code pushes an update frame, copies the arg stack chunk on
4609 top of the stack, and enters the function closure. (It has to do a
4610 stack overflow test first.)
4612 The ``arg stack'' is a block of (tagged) arguments representing the
4613 free variables of the thunk; ``no of arg words'' tells how many words
4614 it consists of. The function closure is (a pointer to) the closure
4615 for the thunk. The argument stack may be empty if the thunk has no
4619 \subsubsection{Indirections}
4621 \label{sect:IND_OLDGEN}
4623 Indirection closures just point to other closures. They are introduced
4624 when a thunk is updated to point to its value.
4625 The entry code for all indirections simply enters the closure it points to.
4627 There are several forms of indirection:
4629 \item[@IND@] is the vanilla, dynamically-allocated indirection.
4630 It is removed by the garbage collector. It has the following
4633 \begin{tabular}{|l|l|l|}\hline
4634 {\em Fixed header} & {\em Target closure} \\ \hline
4638 \item[@IND_OLDGEN@] is the indirection used to update an old-generation
4639 thunk. Its shape is like this:
4641 \begin{tabular}{|l|l|l|}\hline
4642 {\em Fixed header} & {\em Mutable link field} & {\em Target closure} \\ \hline
4645 It contains a {\em mutable link field} that is used to string together
4646 all old-generation indirections that might have a pointer into
4650 \item[@IND_PERMANENT@ and @IND_OLDGEN_PERMANENT@.]
4651 for lexical profiling, it is necessary to maintain cost centre
4652 information in an indirection, so ``permanent indirections'' are
4653 retained forever. Otherwise they are just like vanilla indirections.
4654 \note{If a permanent indirection points to another permanent
4655 indirection or a @CONST@ closure, it is possible to elide the indirection
4656 since it will have no effect on the profiler.}
4657 \note{Do we still need @IND@ and @IND_OLDGEN@
4658 in the profiling build, or can we just make
4659 do with one pair whose behaviour changes when profiling is built?}
4661 \item[@IND_STATIC@] is used for overwriting CAFs when they have been
4662 evaluated. Static indirections are not removed by the garbage
4663 collector; and are statically allocated outside the heap (and should
4664 stay there). Their static object link field is used just as for
4665 @FUN_STATIC@ closures.
4668 \begin{tabular}{|l|l|l|}
4670 {\em Fixed header} & {\em Target closure} & {\em Static object link} \\
4677 \subsubsection{Activation Records}
4679 Activation records are parts of the stack described by return address
4680 info tables (closures with @INFO_TYPE@ values of @RET_SMALL@,
4681 @RET_VEC_SMALL@, @RET_BIG@ and @RET_VEC_BIG@). They are described in
4682 section~\ref{sect:activation-records}.
4685 \subsubsection{Black holes, MVars and IVars}
4690 Black hole closures are used to overwrite closures currently being
4691 evaluated. They inform the garbage collector that there are no live
4692 roots in the closure, thus removing a potential space leak.
4694 Black holes also become synchronization points in the threaded world.
4695 They contain a pointer to a list of blocked threads to be awakened
4696 when the black hole is updated (or @NULL@ if the list is empty).
4698 \begin{tabular}{|l|l|l|}
4700 {\em Fixed header} & {\em Mutable link} & {\em Blocked thread link} \\
4704 The {\em Blocked thread link} points to the TSO of the first thread
4705 waiting for the value of this thunk. All subsequent TSOs in the list
4706 are linked together using their @TSO_LINK@ field.
4708 When the blocking queue is non-@NULL@, the black hole must be added to
4709 the mutables list since the TSOs on the list may contain pointers into
4710 the new generation. There is no need to clutter up the mutables list
4711 with black holes with empty blocking queues.
4716 \subsubsection{FetchMes}\label{sect:FETCHME}
4718 In the parallel systems, FetchMes are used to represent pointers into
4719 the global heap. When evaluated, the value they point to is read from
4722 \ToDo{Describe layout}
4725 \subsection{Unpointed Objects}
4727 A variable of unpointed type is always bound to a {\em value}, never to a {\em thunk}.
4728 For this reason, unpointed objects cannot be entered.
4730 A {\em value} may be:
4732 \item {\em Boxed}, i.e.~represented indirectly by a pointer to a heap object (e.g.~foreign objects, arrays); or
4733 \item {\em Unboxed}, i.e.~represented directly by a bit-pattern in one or more registers (e.g.~@Int#@ and @Float#@).
4735 All {\em pointed} values are {\em boxed}.
4737 \subsubsection{Immutable Objects}
4738 \label{sect:ARR_WORDS1}
4739 \label{sect:ARR_PTRS}
4742 \item[@ARR_WORDS@] is a variable-sized object consisting solely of
4743 non-pointers. It is used for arrays of all
4744 sorts of things (bytes, words, floats, doubles... it doesn't matter).
4746 \begin{tabular}{|c|c|c|c|}
4748 {\em Fixed Hdr} & {\em No of non-pointers} & {\em Non-pointers\ldots} \\ \hline
4752 \item[@ARR_PTRS@] is an immutable, variable sized array of pointers.
4754 \begin{tabular}{|c|c|c|c|}
4756 {\em Fixed Hdr} & {\em Mutable link} & {\em No of pointers} & {\em Pointers\ldots} \\ \hline
4759 The mutable link is present so that we can easily freeze and thaw an
4760 array (by changing the header and adding/removing the array to the
4765 \subsubsection{Mutable Objects}
4766 \label{sect:mutables}
4767 \label{sect:ARR_WORDS2}
4769 \label{sect:MUTARR_PTRS}
4770 \label{sect:MUTARR_PTRS_FROZEN}
4772 Some of these objects are {\em mutable}; they represent objects which
4773 are explicitly mutated by Haskell code through the @ST@ monad.
4774 They're not used for thunks which are updated precisely once.
4775 Depending on the garbage collector, mutable closures may contain extra
4776 header information which allows a generational collector to implement
4777 the ``write barrier.''
4781 \item[@ARR_WORDS@] is also used to represent {\em mutable} arrays of
4782 bytes, words, floats, doubles, etc. It's possible to use the same
4783 object type because even generational collectors don't need to
4786 \item[@MUTVAR@] is a mutable variable.
4788 \begin{tabular}{|c|c|c|}
4790 {\em Fixed Hdr} & {\em Mutable link} & {\em Pointer} \\ \hline
4794 \item[@MUTARR_PTRS@] is a mutable array of pointers.
4795 Such an array may be {\em frozen}, becoming an @SM_MUTARR_PTRS_FROZEN@, with a
4796 different info-table.
4798 \begin{tabular}{|c|c|c|c|}
4800 {\em Fixed Hdr} & {\em Mutable link} & {\em No of ptrs} & {\em Pointers\ldots} \\ \hline
4804 \item[@MUTARR_PTRS_FROZEN@] is a frozen @MUTARR_PTRS@ closure.
4805 The garbage collector converts @MUTARR_PTRS_FROZEN@ to @ARR_PTRS@ as it removes them from
4811 \subsubsection{Foreign Objects}\label{sect:FOREIGN}
4813 Here's what a ForeignObj looks like:
4816 \begin{tabular}{|l|l|l|l|}
4818 {\em Fixed header} & {\em Data} & {\em Free Routine} & {\em Foreign object link} \\
4823 The @FreeRoutine@ is a reference to the finalisation routine to call
4824 when the @ForeignObj@ becomes garbage. If @freeForeignObject@ is
4825 called on a Foreign Object, the @FreeRoutine@ is set to zero and the
4826 garbage collector will not attempt to call @FreeRoutine@ when the
4827 object becomes garbage.
4829 The Foreign object link is a link to the next foreign object in the
4830 list. This list is traversed at the end of garbage collection: if an
4831 object is about to be deallocated (e.g.~it was not marked or
4832 evacuated), the free routine is called and the object is deleted from
4836 The remaining objects types are all administrative --- none of them may be entered.
4838 \subsection{Thread State Objects (TSOs)}\label{sect:TSO}
4840 In the multi-threaded system, the state of a suspended thread is
4841 packed up into a Thread State Object (TSO) which contains all the
4842 information needed to restart the thread and for the garbage collector
4843 to find all reachable objects. When a thread is running, it may be
4844 ``unpacked'' into machine registers and various other memory locations
4845 to provide faster access.
4847 Single-threaded systems don't really {\em need\/} TSOs --- but they do
4848 need some way to tell the storage manager about live roots so it is
4849 convenient to use a single TSO to store the mutator state even in
4850 single-threaded systems.
4852 Rather than manage TSOs' alloc/dealloc, etc., in some {\em ad hoc}
4853 way, we instead alloc/dealloc/etc them in the heap; then we can use
4854 all the standard garbage-collection/fetching/flushing/etc machinery on
4855 them. So that's why TSOs are ``heap objects,'' albeit very special
4858 \begin{tabular}{|l|l|}
4859 \hline {\em Fixed header}
4860 \\ \hline @TSO_LINK@
4861 \\ \hline @TSO_WHATNEXT@
4862 \\ \hline @TSO_WHATNEXT_INFO@
4863 \\ \hline @TSO_STACK@
4864 \\ \hline {\em Exception Handlers}
4865 \\ \hline {\em Ticky Info}
4866 \\ \hline {\em Profiling Info}
4867 \\ \hline {\em Parallel Info}
4868 \\ \hline {\em GranSim Info}
4872 The contents of a TSO are:
4875 \item A pointer (@TSO_LINK@) used to maintain a list of threads with a similar
4876 state (e.g.~all runnable, all sleeping, all blocked on the same black
4877 hole, all blocked on the same MVar, etc.)
4879 \item A word (@TSO_WHATNEXT@) which is in suspended threads to record
4880 how to awaken it. This typically requires a program counter which is stored
4881 in the pointer @TSO_WHATNEXT_INFO@
4883 \item A pointer (@TSO_STACK@) to the top stack block.
4885 \item Optional information for ``Ticky Ticky'' statistics: @TSO_STK_HWM@ is
4886 the maximum number of words allocated to this thread.
4888 \item Optional information for profiling:
4889 @TSO_CCC@ is the current cost centre.
4891 \item Optional information for parallel execution:
4894 \item The types of threads (@TSO_TYPE@):
4896 \item[@T_MAIN@] Must be executed locally.
4897 \item[@T_REQUIRED@] A required thread -- may be exported.
4898 \item[@T_ADVISORY@] An advisory thread -- may be exported.
4899 \item[@T_FAIL@] A failure thread -- may be exported.
4902 \item I've no idea what else
4906 \item Optional information for GranSim execution:
4923 \item clock (gransim light only)
4927 Here are the various queues for GrAnSim-type events.
4938 \subsection{Other weird objects}
4940 \label{sect:BLOCKED_FETCH}
4943 \item[@BlockedFetch@ heap objects (`closures')] (parallel only)
4945 @BlockedFetch@s are inbound fetch messages blocked on local closures.
4946 They arise as entries in a local blocking queue when a fetch has been
4947 received for a local black hole. When awakened, we look at their
4948 contents to figure out where to send a resume.
4950 A @BlockedFetch@ closure has the form:
4952 \begin{tabular}{|l|l|l|l|l|l|}\hline
4953 {\em Fixed header} & link & node & gtid & slot & weight \\ \hline
4957 \item[Spark Closures] (parallel only)
4959 Spark closures are used to link together all closures in the spark pool. When
4960 the current processor is idle, it may choose to speculatively evaluate some of
4961 the closures in the pool. It may also choose to delete sparks from the pool.
4963 \begin{tabular}{|l|l|l|l|l|l|}\hline
4964 {\em Fixed header} & {\em Spark pool link} & {\em Sparked closure} \\ \hline
4972 \subsection{Stack Objects}
4973 \label{sect:STACK_OBJECT}
4976 These are ``stack objects,'' which are used in the threaded world as
4977 the stack for each thread is allocated from the heap in smallish
4978 chunks. (The stack in the sequential world is allocated outside of
4981 Each reduction thread has to have its own stack space. As there may
4982 be many such threads, and as any given one may need quite a big stack,
4983 a naive give-'em-a-big-stack-and-let-'em-run approach will cost a {\em
4986 Our approach is to give a thread a small stack space, and then link
4987 on/off extra ``chunks'' as the need arises. Again, this is a
4988 storage-management problem, and, yet again, we choose to graft the
4989 whole business onto the existing heap-management machinery. So stack
4990 objects will live in the heap, be garbage collected, etc., etc..
4992 A stack object is laid out like this:
4995 \begin{tabular}{|l|}
4999 {\em Link to next stack object (0 for last)}
5001 {\em N, the payload size in words}
5003 {\em @Sp@ (byte offset from head of object)}
5005 {\em @Su@ (byte offset from head of object)}
5007 {\em Payload (N words)}
5012 \ToDo{Are stack objects on the mutable list?}
5014 The stack grows downwards, towards decreasing
5015 addresses. This makes it easier to print out the stack
5016 when debugging, and it means that a return address is
5017 at the lowest address of the chunk of stack it ``knows about''
5018 just like an info pointer on a closure.
5020 The garbage collector needs to be able to find all the
5021 pointers in a stack. How does it do this?
5025 \item Within the stack there are return addresses, pushed
5026 by @case@ expressions. Below a return address (i.e. at higher
5027 memory addresses, since the stack grows downwards) is a chunk
5028 of stack that the return address ``knows about'', namely the
5029 activation record of the currently running function.
5031 \item Below each such activation record is a {\em pending-argument
5032 section}, a chunk of
5033 zero or more words that are the arguments to which the result
5034 of the function should be applied. The return address does not
5036 ``know'' how many pending arguments there are, or their types.
5037 (For example, the function might return a result of type $\alpha$.)
5039 \item Below each pending-argument section is another return address,
5040 and so on. Actually, there might be an update frame instead, but we
5041 can consider update frames as a special case of a return address with
5042 a well-defined activation record.
5044 \ToDo{Doesn't it {\em have} to be an update frame? After all, the arg
5045 satisfaction check is @Su - Sp >= ...@.}
5049 The game plan is this. The garbage collector
5050 walks the stack from the top, traversing pending-argument sections and
5051 activation records alternately. Next we discuss how it finds
5052 the pointers in each of these two stack regions.
5055 \subsubsection{Activation records}\label{sect:activation-records}
5057 An {\em activation record} is a contiguous chunk of stack,
5058 with a return address as its first word, followed by as many
5059 data words as the return address ``knows about''. The return
5060 address is actually a fully-fledged info pointer. It points
5061 to an info table, replete with:
5064 \item entry code (i.e. the code to return to).
5065 \item @INFO_TYPE@ is either @RET_SMALL/RET_VEC_SMALL@ or @RET_BIG/RET_VEC_BIG@, depending
5066 on whether the activation record has more than 32 data words (\note{64 for 8-byte-word architectures}) and on whether
5067 to use a direct or a vectored return.
5068 \item @INFO_SM@ for @RET_SMALL@ is a bitmap telling the layout
5069 of the activation record, one bit per word. The least-significant bit
5070 describes the first data word of the record (adjacent to the fixed
5071 header) and so on. A ``@1@'' indicates a non-pointer, a ``@0@''
5073 a pointer. We don't need to indicate exactly how many words there
5075 because when we get to all zeros we can treat the rest of the
5076 activation record as part of the next pending-argument region.
5078 For @RET_BIG@ the @INFO_SM@ field points to a block of bitmap
5079 words, starting with a word that tells how many words are in
5082 \item @INFO_SRT@ is the Static Reference Table for the return
5083 address (Section~\ref{sect:srt}).
5086 The activation record is a fully fledged closure too.
5087 As well as an info pointer, it has all the other attributes of
5088 a fixed header (Section~\ref{sect:fixed-header}) including a saved cost
5089 centre which is reloaded when the return address is entered.
5091 In other words, all the attributes of closures are needed for
5092 activation records, so it's very convenient to make them look alike.
5095 \subsubsection{Pending arguments}
5097 So that the garbage collector can correctly identify pointers
5098 in pending-argument sections we explicitly tag all non-pointers.
5099 Every non-pointer in a pending-argument section is preceded
5100 (at the next lower memory word) by a one-word byte count that
5101 says how many bytes to skip over (excluding the tag word).
5103 The garbage collector traverses a pending argument section from
5104 the top (i.e. lowest memory address). It looks at each word in turn:
5107 \item If it is less than or equal to a small constant @MAX_STACK_TAG@
5109 it treats it as a tag heralding zero or more words of non-pointers,
5110 so it just skips over them.
5112 \item If it points to the code segment, it must be a return
5113 address, so we have come to the end of the pending-argument section.
5115 \item Otherwise it must be a bona fide heap pointer.
5119 \subsection{The Stable Pointer Table}\label{sect:STABLEPTR_TABLE}
5121 A stable pointer is a name for a Haskell object which can be passed to
5122 the external world. It is ``stable'' in the sense that the name does
5123 not change when the Haskell garbage collector runs---in contrast to
5124 the address of the object which may well change.
5126 A stable pointer is represented by an index into the
5127 @StablePointerTable@. The Haskell garbage collector treats the
5128 @StablePointerTable@ as a source of roots for GC.
5130 In order to provide efficient access to stable pointers and to be able
5131 to cope with any number of stable pointers (eg $0 \ldots 100000$), the
5132 table of stable pointers is an array stored on the heap and can grow
5133 when it overflows. (Since we cannot compact the table by moving
5134 stable pointers about, it seems unlikely that a half-empty table can
5135 be reduced in size---this could be fixed if necessary by using a
5136 hash table of some sort.)
5138 In general a stable pointer table closure looks like this:
5141 \begin{tabular}{|l|l|l|l|l|l|l|l|l|l|l|}
5143 {\em Fixed header} & {\em No of pointers} & {\em Free} & $SP_0$ & \ldots & $SP_{n-1}$
5151 \item[@NPtrs@:] number of (stable) pointers.
5153 \item[@Free@:] the byte offset (from the first byte of the object) of the first free stable pointer.
5155 \item[$SP_i$:] A stable pointer slot. If this entry is in use, it is
5156 an ``unstable'' pointer to a closure. If this entry is not in use, it
5157 is a byte offset of the next free stable pointer slot.
5161 When a stable pointer table is evacuated
5163 \item the free list entries are all set to @NULL@ so that the evacuation
5164 code knows they're not pointers;
5166 \item The stable pointer slots are scanned linearly: non-@NULL@ slots
5167 are evacuated and @NULL@-values are chained together to form a new free list.
5170 There's no need to link the stable pointer table onto the mutable
5171 list because we always treat it as a root.
5175 \section{The Storage Manager}
5177 The generational collector remembers the depth of the last generation
5178 collected and the value of the heap pointer at the end of the last GC.
5179 If the mutator has not moved the heap pointer, that means that the
5180 amount of space recovered is insufficient to satisfy even one request
5181 and it is time to collect an older generation or report a heap overflow.
5183 A deeper collection is also triggered when a minor collection fails to
5184 recover at least @...@ bytes of space.
5186 When can a GC happen?
5189 - During updates (ie during returns)
5190 - When a heap check fails
5191 - When a stack check fails (concurrent system only)
5192 - When a context switch happens (concurrent system only)
5194 When do heap checks occur?
5195 - Immediately after entering a thunk
5196 - Immediately after entering a case alternative
5198 When do stack checks occur?
5199 - We calculate the worst-case stack usage of an entire
5200 thunk so there's no need to put a check inside each alternative.
5201 - Immediately after entering a thunk
5202 We can't make a similar worst-case calculation for heap usage
5203 because the heap isn't used in a stacklike manner so any
5204 evaluation inside a case might steal some of the heap we've
5208 - Threads can be blocked
5209 - Threads can be put to sleep
5210 - Heap may move while we sleep
5211 - Black holing may happen while we sleep (ie during GC)
5214 \subsection{The SM state}
5216 Contains @Hp@, @HpLim@, @StablePtrTable@ plus version-specific info.
5220 \item Static Object list
5221 \item Foreign Object list
5222 \item Stable Pointer Table
5226 In addition, the generational collector requires:
5230 \item Old Generation Indirection list
5231 \item Mutables list --- list of mutable objects in the old generation.
5232 \item @OldLim@ --- the boundary between the generations
5233 \item Old Foreign Object list --- foreign objects in the old generation
5237 It is passed a table of {\em roots\/} containing
5241 \item All runnable TSOs
5246 In the parallel system, there must be some extra magic associated with
5249 \subsection{The SM interface}
5251 @initSM@ finalizes any runtime parameters of the storage manager.
5253 @exitSM@ does any cleaning up required by the storage manager before
5254 the program is executed. Its main purpose is to print any summary
5257 @initHeap@ allocates the heap. It initialises the @hp@ and @hplim@
5258 fields of @sm@ to represent an empty heap for the compiled-in garbage
5259 collector. It also initialises @CAFlist@ to be the empty list. If we
5260 are using Appel's collector it also initialises the @OldLim@ field.
5261 It also initialises the stable pointer table and the @ForeignObjList@
5262 (and @OldForeignObjList@) fields.
5264 @collectHeap@ invokes the garbage collector. @collectHeap@ requires
5265 all the fields of @sm@ to be initialised appropriately (from the
5266 STG-machine registers). The following are identified as heap roots:
5268 \item The updated CAFs recorded in @CAFlist@.
5269 \item Any pointers found on the stack.
5270 \item All runnable and sleeping TSOs.
5271 \item The stable pointer table.
5274 There are two possible results from a garbage collection:
5277 The garbage collector is unable to free up any more space.
5280 The garbage collector managed to free up more space.
5283 \item @hp@ and @hplim@ will indicate the new space available for
5286 \item The elements of @CAFlist@ and the stable pointers will be
5287 updated to point to the new locations of the closures they reference.
5289 \item Any members of @ForeignObjList@ which became garbage should have
5290 been reported (by calling their finalising routines; and the
5291 @(Old)ForeignObjList@ updated to contain only those Foreign objects
5292 which are still live.
5298 %************************************************************************
5300 \subsection{``What really happens in a garbage collection?''}
5302 %************************************************************************
5304 \ToDo{I commented out this long, out of date section - ADR}
5308 This is a brief tutorial on ``what really happens'' going to/from the
5309 storage manager in a garbage collection.
5312 %------------------------------------------------------------------------
5313 \item[The heap check:]
5317 If you gaze into the C output of GHC, you see many macros calls like:
5319 HEAP_CHK_2PtrsLive((_FHS+2));
5322 This expands into the C (roughly speaking...):
5324 Hp = Hp + (_FHS+2); /* optimistically move heap pointer forward */
5326 GC_WHILE_OR_IF (HEAP_OVERFLOW_OP(Hp, HpLim) OR_INTERVAL_EXPIRED) {
5327 STGCALL2_GC(PerformGC, <liveness-bits>, (_FHS+2));
5331 In the parallel world, where we will need to re-try the heap check,
5332 @GC_WHILE_OR_IF@ will be a ``while''; in the sequential world, it will
5335 The ``heap lookahead'' checks, which are similar and used for
5336 multi-precision @Integer@ ops, have some further complications. See
5337 the commentary there (@StgMacros.lh@).
5339 %------------------------------------------------------------------------
5340 \item[Into @callWrapper_GC@...:]
5342 When we failed the heap check (above), we were inside the
5343 GCC-registerised ``threaded world.'' @callWrapper_GC@ is all about
5344 getting in and out of the threaded world. On SPARCs, with register
5345 windows, the name of the game is not shifting windows until we have
5346 what we want out of the old one. In tricky cases like this, it's best
5347 written in assembly language.
5349 Performing a GC (potentially) means giving up the thread of control.
5350 So we must fill in the thread-state-object (TSO) [and its associated
5351 stk object] with enough information for later resumption:
5354 Save the return address in the TSO's PC field.
5356 Save the machine registers used in the STG threaded world in their
5357 corresponding TSO fields. We also save the pointer-liveness
5358 information in the TSO.
5360 The registers that are not thread-specific, notably @Hp@ and
5361 @HpLim@, are saved in the @StorageMgrInfo@ structure.
5363 Call the routine it was asked to call; in this example, call
5364 @PerformGC@ with arguments @<liveness>@ and @_FHS+2@ (some constant)...
5368 %------------------------------------------------------------------------
5369 \item[Into the heap overflow wrapper, @PerformGC@ [parallel]:]
5371 Most information has already been saved in the TSO.
5375 The first argument (@<liveness>@, in our example) say what registers
5376 are live, i.e., are ``roots'' the storage manager needs to know.
5378 StorageMgrInfo.rootno = 2;
5379 StorageMgrInfo.roots[0] = (P_) Ret1_SAVE;
5380 StorageMgrInfo.roots[1] = (P_) Ret2_SAVE;
5384 We move the heap-pointer back [we had optimistically
5385 advanced it, in the initial heap check]
5388 We load up the @smInfo@ data from the STG registers' @*_SAVE@ locations.
5391 We mark on the scheduler's big ``blackboard'' that a GC is
5395 We reschedule, i.e., this thread gives up control. (The scheduler
5396 will presumably initiate a garbage-collection, but it may have to do
5397 any number of other things---flushing, for example---before ``normal
5398 execution'' resumes; and it most certainly may not be this thread that
5399 resumes at that point!)
5402 IT IS AT THIS POINT THAT THE WORLD IS COMPLETELY TIDY.
5404 %------------------------------------------------------------------------
5405 \item[Out of @callWrapper_GC@ [parallel]:]
5407 When this thread is finally resumed after GC (and who knows what
5408 else), it will restart by the normal enter-TSO/enter-stack-object
5409 sequence, which has the effect of re-loading the registers, etc.,
5410 (i.e., restoring the state).
5412 Because the address we saved in the TSO's PC field was that at the end
5413 of the heap check, and because the check is a while-loop in the
5414 parallel system, we will now loop back around, and make sure there is
5415 enough space before continuing.
5418 \fi % end of commented out part
5420 \subsection{Static Reference Tables (SRTs)}
5423 \label{sect:static-objects}
5425 In the above, we assumed that objects always contained pointers to all
5426 their free variables. In fact, this isn't quite true: GHC omits
5427 pointers to top-level objects and allocates their closures in static
5428 memory. This optimisation reduces the number of free variables in
5429 heap objects - reducing memory usage and the effort needed to put them
5430 into heap objects. However, this optimisation comes at a cost: we
5431 need to complicate the garbage collector with machinery for tracing
5432 these static references.
5434 Early versions of GHC used a very simple algorithm: it treated all
5435 static objects as roots. This is safe in the sense that no object is
5436 ever deallocated if there's a chance that it might be required later
5437 but can lead to some terrible space leaks. For example, this program
5438 ought to be able to run in constant space but, because @xs@ is never
5439 deallocated, it runs in linear space.
5446 The correct behaviour is for the garbage collector to keep a static
5447 object alive iff it might be required later in execution. That is, if
5448 it is reachable from any live heap objects {\em or\/} from any return
5449 addresses found on the stack or from the current program counter.
5450 Since it is obviously infeasible for the garbage collector to scan
5451 machine code looking for static references, the code generator must
5452 generate a table of all static references in any piece of code (and we
5453 must place a pointer to this table next to any piece of code we
5456 Here's what the SRT has to contain:
5462 Here's how we represent it:
5466 must be able to handle 0 references well
5473 o Generational GC trickery
5476 \subsection{Space leaks and black holes}
5477 \label{sect:black-hole}
5481 \ToDo{Insert text stolen from update paper}
5485 A program exhibits a {\em space leak} if it retains storage that is
5486 sure not to be used again. Space leaks are becoming increasingly
5487 common in imperative programs that @malloc@ storage and fail
5488 subsequently to @free@ it. They are, however, also common in
5489 garbage-collected systems, especially where lazy evaluation is
5490 used.[.wadler leak, runciman heap profiling jfp.]
5492 Quite a bit of experience has now accumulated suggesting that
5493 implementors must be very conscientious about avoiding gratuitous
5494 space leaks --- that is, ones which are an accidental artefact of some
5495 implementation technique.[.appel book.] The update mechanism is
5496 a case in point, as <.jones jfp leak.> points out. Consider a thunk for
5499 let xs = [1..1000] in last xs
5501 where @last@ is a function that returns the last element of its
5502 argument list. When the thunk is entered it will call @last@, which
5503 will consume @xs@ until it finds the last element. Since the list
5504 @[1..1000]@ is produced lazily one might reasonably expect the
5505 expression to evaluate in constant space. But {\em until the moment
5506 of update, the thunk itself still retains a pointer to the beginning
5507 of the list @xs@}. So, until the update takes place the whole list
5510 Of course, this is completely gratuitous. The pointer to @xs@ in the
5511 thunk will never be used again. In <.peyton stock hardware.> the solution to
5512 this problem that we advocated was to overwrite a thunk's info with a
5513 fixed ``black hole'' info pointer, {\em at the moment of entry}. The
5514 storage management information attached to a black-hole info pointer
5515 tells the garbage collector that the closure contains no pointers,
5516 thereby plugging the space leak.
5518 \subsubsection{Lazy black-holing}
5519 \label{sect:lazy-black-holing}
5521 \Note{We currently plan to implement eager black holing because the
5522 lazy blackholing scheme leavs "slop" in the heap.}
5524 Black-holing is a well-known idea. The trouble is that it is
5525 gallingly expensive. To avoid the occasional space leak, for every
5526 single thunk entry we have to load a full-word literal constant into a
5527 register (often two instructions) and then store that register into a
5530 Fortunately, this cost can easily be avoided. The
5531 idea is simple: {\em instead of black-holing every thunk on entry,
5532 wait until the garbage collector is called, and then black-hole all
5533 (and only) the thunks whose evaluation is in progress at that moment}.
5534 There is no benefit in black-holing a thunk that is updated before
5535 garbage collection strikes! In effect, the idea is to perform the
5536 black-holing operation lazily, only when it is needed. This
5537 dramatically cuts down the number of black-holing operations, as our
5538 results show {\em forward ref}.
5540 How can we find all the thunks whose evaluation is in progress? They
5541 are precisely the ones for which update frames are on the stack. So
5542 all we need do is find all the update frames (via the @Su@ chain) and
5543 black-hole their thunks right at the start of garbage collection.
5544 Notice that it is not enough to refrain from treating update frames as
5545 roots: firstly because the thunks to which they point may need to be
5546 moved in a copying collector, but more importantly because the thunk
5547 might be accessible via some other route.
5549 \subsubsection{Detecting loops}
5551 Black-holing has a second minor advantage: evaluation of a thunk whose
5552 value depends on itself will cause a black hole closure to be entered,
5553 which can cause a suitable error message to be displayed. For example,
5554 consider the definition
5558 The code to evaluate @x@'s right hand side will evaluate @x@. In the
5559 absence of black-holing, the result will be a stack overflow, as the
5560 evaluator repeatedly pushes a return address and enters @x@. If
5561 thunks are black-holed on entry, then this infinite loop can be caught
5564 With our new method of lazy black-holing, a self-referential program
5565 might cause either stack overflow or a black-hole error message,
5566 depending on exactly when garbage collection strikes. It is quite
5567 easy to conceal these differences, however. If stack overflow occurs,
5568 all we need do is examine the update frames on the stack to see if
5569 more than one refers to the same thunk. If so, there is a loop that
5570 would have been detected by eager black-holing.
5572 \subsubsection{Lazy locking}
5575 In a parallel implementation, it is necessary somehow to ``lock'' a
5576 thunk that is under evaluation, so that other parallel evaluators
5577 cannot simultaneously evaluate it and thereby duplicate work.
5578 Instead, an evaluator that enters a locked thunk should be blocked,
5579 and made runnable again when the thunk is updated.
5581 This locking is readily arranged in the same way as black-holing, by
5582 overwriting the thunk's info pointer with a special ``locked'' info
5583 pointer, at the moment of entry. If another evaluator enters the
5584 thunk before it has been updated, it will land in the entry code for
5585 the ``locked'' info pointer, which blocks the evaluator and queues it
5586 on the locked thunk.
5588 The details are given by <.portable parallel trinder.>. However, the close similarity
5589 between locking and black holing suggests the following question: can
5590 locking be done lazily too? The answer is that it can, except that
5591 locking can be postponed only until the next {\em context switch},
5592 rather than the next {\em garbage collection}. We are assuming here
5593 that the parallel implementation does not use shared memory to allow
5594 two processors to access the same closure. If such access is
5595 permitted then every thunk entry requires a hardware lock, and becomes
5598 Is lazy locking worth while, given that it requires extra work every
5599 context switch? We believe it is, because contexts switches are
5600 relatively infrequent, and thousands of thunk-entries typically take
5603 {\em Measurements elsewhere. Omit this section? If so, fix cross refs to here.}
5608 \subsection{Squeezing identical updates}
5610 \Note{This can also be done by testing whether @Sp == Su@ when we push
5611 an update frame. If so, we can overwrite the updatee with an
5612 indirection to the existing updatee (and some slop objects) and avoid
5613 pushing an update frame.}
5617 \ToDo{Insert text stolen from update paper}
5621 Consider the following Haskell definition of the standard
5622 function @partition@ that divides a list into two, those elements
5623 that satisfy a predicate @p@ and those that do not:
5625 partition :: (a->Bool) -> [a] -> ([a],[a])
5626 partition p [] = ([],[])
5627 partition p (x:xs) = if p x then (x:ys, zs)
5630 (ys,zs) = partition p xs
5632 By the time this definition has been desugared, it looks like this:
5642 if p x then (x:ys,zs)
5645 Lazy evaluation demands that the recursive call is bound to an
5646 intermediate variable, @t@, from which @ys@ and @zs@ are lazily
5647 selected. (The functions @fst@ and @snd@ select the first and second
5648 elements of a pair, respectively.)
5650 Now, suppose that @partition@ is applied to a list @[x1,x2]@,
5652 elements satisfy @p@. We can get a good idea of what will happen
5653 at runtime by unrolling the recursion a few times in our heads.
5654 Unrolling once, and remembering that @(p x1)@ is @True@, we get this:
5658 let t1 = partition [x2]
5663 Unrolling the rest of the way gives this:
5675 Now consider what happens if @zs1@ is evaluated. It is bound to a
5676 thunk, which will push an update frame before evaluating the
5677 expression @snd t1@. This expression in turn forces evaluation of
5678 @zs2@, which pushes an update frame before evaluating @snd t2@.
5679 Indeed the stack of update frames will grow as deep as the list is
5680 long when @zs1@ is evaluated. This is rather galling, since all the
5681 thunks @zs1@, @zs2@, and so on, have the same value.
5683 \ToDo{Describe the state-transformer case in which we get a space leak from
5684 pending update frames.}
5686 The solution is simple. The garbage collector, which is going to traverse the
5687 update stack in any case, can easily identify two update frames that are directly
5688 on top of each other. The second of these will update its target with the same
5689 value as the first. Therefore, the garbage collector can perform the update
5690 right away, by overwriting one update target with an indirection to the second,
5691 and eliminate the corresponding update frame. In this way ever-growing stacks of
5692 update frames are reduced to a single representative at garbage collection time.
5693 If this is done at the start of garbage collection then, if it turns out that
5694 some of these update targets are garbage they will be collected right away.
5698 \subsection{Space leaks and selectors}\label{sect:space-leaks-and-selectors}
5702 \ToDo{Insert text stolen from update paper}
5706 In 1987, Wadler identified an important source of space leaks in
5707 lazy functional programs. Consider the Haskell function definition:
5709 f p = (g1 a, g2 b) where (a,b) = p
5711 The pattern-matching in the @where@ clause is known as
5712 {\em lazy pattern-matching}, because it is performed only if @a@
5713 or @b@ is actually evaluated. The desugarer translates lazy pattern matching
5714 to the use of selectors, @fst@ and @snd@ in this case:
5721 Now suppose that the second component of the pair @(f p)@, namely @a@,
5722 is evaluated and discarded, but the first is not although it remains
5723 reachable. The garbage collector will find that the thunk for @b@ refers
5724 to @p@ and hence to @a@. Thus, although @a@ cannot ever be used again, its
5725 space is retained. It turns out that this space leak can have a very bad effect
5726 indeed on a program's space behaviour (Section~\ref{sect:selector-results}).
5728 Wadler's paper also proposed a solution: if the garbage collector
5729 encounters a thunk of the form @snd p@, where @p@ is evaluated, then
5730 the garbage collector should perform the selection and overwrite the
5731 thunk with a pointer to the second component of the pair. In effect, the
5732 garbage collector thereby performs a bounded amount of as-yet-undemanded evaluation
5733 in the hope of improving space behaviour.
5734 We implement this idea directly, by making the garbage collector
5735 eagerly execute all selector thunks\footnote{A word of caution: it is rather easy
5736 to make a mistake in the implementation, especially if the garbage collector
5737 uses pointer reversal to traverse the reachable graph.},
5739 reported in Section~\ref{sect:THUNK_SEL}.
5741 One could easily imagine generalisations of this idea, with the garbage
5742 collector performing bounded amounts of space-saving work. One example is
5746 f x (y:ys) = f (x+1) ys
5748 Most lazy evaluators will build up a chain of thunks for the accumulating
5749 parameter, @x@, each of which increments @x@. It is not safe to evaluate
5750 any of these thunks eagerly, since @f@ is not strict in @x@, and we know nothing
5751 about the value of @x@ passed in the initial call to @f@.
5752 On the other hand, if the garbage collector found a thunk @(x+1)@ where
5753 @x@ happened to be evaluated, then it could ``execute'' it eagerly.
5754 If done carefully, the entire chain could be eliminated in a single
5755 garbage collection. We have not (yet) implemented this idea.
5756 A very similar idea, dubbed ``stingy evaluation'', is described
5759 \ToDo{Simple generalisation: handle all the ``standard closures'' this way.}
5761 <.sparud lazy pattern matching.> describes another solution to the
5762 lazy-pattern-matching
5763 problem. His solution involves adding code to the two thunks for
5764 @a@ and @b@ so that if either is evaluated it arranges to update the
5765 other as well as itself. The garbage-collector solution is a little
5766 more general, since it applies whether or not the selectors were
5767 generated by lazy pattern matching, and in our setting it was easier
5768 to implement than Sparud's.
5773 \subsection{Internal workings of the Compacting Collector}
5775 \subsection{Internal workings of the Copying Collector}
5777 \subsection{Internal workings of the Generational Collector}
5782 Registering costs centres looks awkward - can we tidy it up?
5784 \section{Parallelism}
5786 Something about global GC, inter-process messages and fetchmes.
5790 \section{Ticky Ticky profiling}
5792 Measure what proportion of ...:
5795 ... Enters are to data values, function values, thunks.
5797 ... allocations are for data values, functions values, thunks.
5799 ... updates are for data values, function values.
5803 ... return-in-heap (dynamic)
5805 ... vectored return (dynamic)
5807 ... updates are wasted (never re-entered).
5809 ... constructor returns get away without hitting an update.
5812 %************************************************************************
5814 \subsection[ticky-stk-heap-use]{Stack and heap usage}
5816 %************************************************************************
5818 Things we are interested in here:
5821 How many times we do a heap check and move @Hp@; comparing this with
5822 the allocations gives an indication of how many things we get per trip
5825 If we do a ``heap lookahead,'' we haven't really allocated any
5826 heap, so we need to undo the effects of an @ALLOC_HEAP@:
5829 The stack high-water mark.
5832 Re-use of stack slots, and stubbing of stack slots:
5836 %************************************************************************
5838 \subsection[ticky-allocs]{Allocations}
5840 %************************************************************************
5842 We count things every time we allocate something in the dynamic heap.
5843 For each, we count the number of words of (1)~``admin'' (header),
5844 (2)~good stuff (useful pointers and data), and (3)~``slop'' (extra
5845 space, in hopes it will allow an in-place update).
5847 The first five macros are inserted when the compiler generates code
5848 to allocate something; the categories correspond to the @ClosureClass@
5849 datatype (manifest functions, thunks, constructors, big tuples, and
5850 partial applications).
5852 We may also allocate space when we do an update, and there isn't
5853 enough space. These macros suffice (for: updating with a partial
5854 application and a constructor):
5856 In the threaded world, we allocate space for the spark pool, stack objects,
5857 and thread state objects.
5859 The histogrammy bit is fairly straightforward; the @-2@ is: one for
5860 0-origin C arrays; the other one because we do {\em no} one-word
5861 allocations, so we would never inc that histogram slot; so we shift
5862 everything over by one.
5864 Some hard-to-account-for words are allocated by/for primitives,
5865 includes Integer support. @ALLOC_PRIM2@ tells us about these. We
5866 count everything as ``goods'', which is not strictly correct.
5867 (@ALLOC_PRIM@ is the same sort of stuff, but we know the
5868 admin/goods/slop breakdown.)
5870 %************************************************************************
5872 \subsection[ticky-enters]{Enters}
5874 %************************************************************************
5876 We do more magical things with @ENT_FUN_DIRECT@. Besides simply knowing
5877 how many ``fast-entry-point'' enters there were, we'd like {\em simple}
5878 information about where those enters were, and the properties thereof.
5880 struct ent_counter {
5881 unsigned registeredp:16, /* 0 == no, 1 == yes */
5882 arity:16, /* arity (static info) */
5883 Astk_args:16, /* # of args off A stack */
5884 Bstk_args:16; /* # of args off B stack */
5885 /* (rest of args are in registers) */
5886 StgChar *f_str; /* name of the thing */
5887 StgChar *f_arg_kinds; /* info about the args types */
5888 StgChar *wrap_str; /* name of its wrapper (if any) */
5889 StgChar *wrap_arg_kinds;/* info about the orig wrapper's arg types */
5890 I_ ctr; /* the actual counter */
5891 struct ent_counter *link; /* link to chain them all together */
5895 %************************************************************************
5897 \subsection[ticky-returns]{Returns}
5899 %************************************************************************
5901 Whenever a ``return'' occurs, it is returning the constituent parts of
5902 a data constructor. The parts can be returned either in registers, or
5903 by allocating some heap to put it in (the @ALLOC_*@ macros account for
5904 the allocation). The constructor can either be an existing one
5905 (@*OLD*@) or we could have {\em just} figured out this stuff
5908 Here's some special magic that Simon wants [edited to match names
5912 From: Simon L Peyton Jones <simonpj>
5913 To: partain, simonpj
5914 Subject: counting updates
5915 Date: Wed, 25 Mar 92 08:39:48 +0000
5917 I'd like to count how many times we update in place when actually Node
5918 points to the thing. Here's how:
5920 @RET_OLD_IN_REGS@ sets the variable @ReturnInRegsNodeValid@ to @True@;
5921 @RET_NEW_IN_REGS@ sets it to @False@.
5923 @RET_SEMI_???@ sets it to??? ToDo [WDP]
5925 @UPD_CON_IN_PLACE@ tests the variable, and increments @UPD_IN_PLACE_COPY_ctr@
5928 Then we need to report it along with the update-in-place info.
5932 Of all the returns (sum of four categories above), how many were
5933 vectored? (The rest were obviously unvectored).
5935 %************************************************************************
5937 \subsection[ticky-update-frames]{Update frames}
5939 %************************************************************************
5941 These macros count up the following update information.
5943 \begin{tabular}{|l|l|} \hline
5944 Macro & Counts \\ \hline
5946 @UPDF_STD_PUSHED@ & Update frame pushed \\
5947 @UPDF_CON_PUSHED@ & Constructor update frame pushed \\
5948 @UPDF_HOLE_PUSHED@ & An update frame to update a black hole \\
5949 @UPDF_OMITTED@ & A thunk decided not to push an update frame \\
5950 & (all subsets of @ENT_THK@) \\
5951 @UPDF_RCC_PUSHED@ & Cost Centre restore frame pushed \\
5952 @UPDF_RCC_OMITTED@ & Cost Centres not required -- not pushed \\\hline
5955 %************************************************************************
5957 \subsection[ticky-updates]{Updates}
5959 %************************************************************************
5961 These macros record information when we do an update. We always
5962 update either with a data constructor (CON) or a partial application
5965 \begin{tabular}{|l|l|}\hline
5966 Macro & Where \\ \hline
5968 @UPD_EXISTING@ & Updating with an indirection to something \\
5969 & already in the heap \\
5970 @UPD_SQUEEZED@ & Same as @UPD_EXISTING@ but because \\
5971 & of stack-squeezing \\
5972 @UPD_CON_W_NODE@ & Updating with a CON: by indirecting to Node \\
5973 @UPD_CON_IN_PLACE@ & Ditto, but in place \\
5974 @UPD_CON_IN_NEW@ & Ditto, but allocating the object \\
5975 @UPD_PAP_IN_PLACE@ & Same, but updating w/ a PAP \\
5976 @UPD_PAP_IN_NEW@ & \\\hline
5979 %************************************************************************
5981 \subsection[ticky-selectors]{Doing selectors at GC time}
5983 %************************************************************************
5985 @GC_SEL_ABANDONED@: we could've done the selection, but we gave up
5986 (e.g., to avoid overflowing the C stack); @GC_SEL_MINOR@: did a
5987 selection in a minor GC; @GC_SEL_MAJOR@: ditto, but major GC.
5993 We're nuking the following:
6000 Return in registers.
6001 This lets us remove update code pointers from info tables,
6002 removes the need for phantom info tables, simplifies
6007 Careful analysis suggests that it doesn't buy us very much
6008 and it is hard to work with.
6010 Eliminating threaded GCs eliminates the desire to share SMReps
6011 so they are (once more) part of the Info table.
6015 Doesn't buy us anything on a register-poor architecture and
6016 isn't so important if we have semi-tagging.
6019 - Probably bad on register poor architecture
6020 - Can avoid need to write return address to stack on reg rich arch.
6021 - when a function does a small amount of work, doesn't
6022 enter any other thunks and then returns.
6023 eg entering a known constructor (but semitagging will catch this)
6024 - Adds complications
6030 This lets us drop CONST closures and CHARLIKE closures (assuming we
6031 don't support Unicode). The only point of these closures was to
6032 avoid updating with an indirection.
6034 We also drop @MIN_UPD_SIZE@ --- all we need is space to insert an
6035 indirection or a black hole.
6038 STATIC SMReps are now called CONST
6043 \item The profiling ``kind'' field is now encoded in the @INFO_TYPE@ field.
6044 This identifies the general sort of the closure for profiling purposes.
6046 \item Various papers describe deleting update frames for unreachable objects.
6047 This has never been implemented and we don't plan to anytime soon.
6051 \section{Old tricks}
6055 These are statically defined closures which have been updated with a
6056 heap-allocated result. Initially these are exactly the same as a
6057 @STATIC@ closure but with special entry code. On entering the closure
6058 the entry code must:
6061 \item Allocate a black hole in the heap which will be updated with
6063 \item Overwrite the static closure with a special @CAF@ indirection.
6065 \item Link the static indirection onto the list of updated @CAF@s.
6068 The indirection and the link field require the initial @STATIC@
6069 closure to be of at least size @MIN_UPD_SIZE@ (excluding the fixed
6072 @CAF@s are treated as special garbage collection roots. These roots
6073 are explicitly collected by the garbage collector, since they may
6074 appear in code even if they are not linked with the main heap. They
6075 consequently represent potentially enormous space-leaks. A @CAF@
6076 closure retains a fixed location in statically allocated data space.
6077 When updated, the contents of the @CAF@ indirection are changed to
6078 reflect the new closure. @CAF@ indirections require special garbage
6081 \section{Old stuff about SRTs}
6083 \ToDo{Commented out}
6087 Garbage collection of @CAF@s is tricky. We have to cope with explicit
6088 collection from the @CAFlist@ as well as potential references from the
6089 stack and heap which will cause the @CAF@ evacuation code to be
6090 called. They are treated like indirections which are shorted out.
6091 However they must also be updated to point to the new location of the
6092 new closure as the @CAF@ may still be used by references which
6095 {\bf Copying Collection}
6097 A first scheme might use evacuation code which evacuates the reference
6098 and updates the indirection. This is no good as subsequent evacuations
6099 will result in an already evacuated closure being evacuated. This will
6100 leave a forward reference in to-space!
6102 An alternative scheme evacuates the @CAFlist@ first. The closures
6103 referenced are evacuated and the @CAF@ indirection updated to point to
6104 the evacuated closure. The @CAF@ evacuation code simply returns the
6105 updated indirection pointer --- the pointer to the evacuated closure.
6106 Unfortunately the closure the @CAF@ references may be a static
6107 closure, in fact, it may be another @CAF@. This will cause the second
6108 @CAF@'s evacuation code to be called before the @CAF@ has been
6109 evacuated, returning an unevacuated pointer.
6111 Another scheme leaves updating the @CAF@ indirections to the end of
6112 the garbage collection. All the references are evacuated and
6113 scavenged as usual (including the @CAFlist@). Once collection is
6114 complete the @CAFlist@ is traversed updating the @CAF@ references with
6115 the result of evacuating the referenced closure again. This will
6116 immediately return as it must be a forward reference, a static
6117 closure, or a @CAF@ which will indirect by evacuating its reference.
6119 The crux of the problem is that the @CAF@ evacuation code needs to
6120 know if its reference has already been evacuated and updated. If not,
6121 then the reference can be evacuated, updated and returned safely
6122 (possibly evacuating another @CAF@). If it has, then the updated
6123 reference can be returned. This can be done using two @CAF@
6124 info-tables. At the start of a collection the @CAFlist@ is traversed
6125 and set to an internal {\em evacuate and update} info-table. During
6126 collection, evacution of such a @CAF@ also results in the info-table
6127 being reset back to the standard @CAF@ info-table. Thus subsequent
6128 evacuations will simply return the updated reference. On completion of
6129 the collection all @CAF@s will have {\em return reference} info-tables
6132 This is the scheme we adopt. A @CAF@ indirection has evacuation code
6133 which returns the evacuated and updated reference. During garbage
6134 collection, all the @CAF@s are overwritten with an internal @CAF@ info
6135 table which has evacuation code which performs this evacuate and
6136 update and restores the original @CAF@ code. At some point during the
6137 collection we must ensure that all the @CAF@s are indeed evacuated.
6139 The only potential problem with this scheme is a cyclic list of @CAF@s
6140 all directly referencing (possibly via indirections) another @CAF@!
6141 Evacuation of the first @CAF@ will fail in an infinite loop of @CAF@
6142 evacuations. This is solved by ensuring that the @CAF@ info-table is
6143 updated to a {\em return reference} info-table before performing the
6144 evacuate and update. If this {\em return reference} evacuation code is
6145 called before the actual evacuation is complete it must be because
6146 such a cycle of references exists. Returning the still unevacuated
6147 reference is OK --- all the @CAF@s will now reference the same
6148 @CAF@ which will reference itself! Construction of such a structure
6149 indicates the program must be in an infinite loop.
6151 {\bf Compacting Collector}
6153 When shorting out a @CAF@, its reference must be marked. A first
6154 attempt might explicitly mark the @CAF@s, updating the reference with
6155 the marked reference (possibly short circuting indirections). The
6156 actual @CAF@ marking code can indicate that they have already been
6157 marked (though this might not have actually been done yet) and return
6158 the indirection pointer so it is shorted out. Unfortunately the @CAF@
6159 reference might point to an indirection which will be subsequently
6160 shorted out. Rather than returning the @CAF@ reference we treat the
6161 @CAF@ as an indirection, calling the mark code of the reference, which
6162 will return the appropriately shorted reference.
6164 Problem: Cyclic list of @CAF@s all directly referencing (possibly via
6165 indirections) another @CAF@!
6167 Before compacting, the locations of the @CAF@ references are
6168 explicitly linked to the closures they reference (if they reference
6169 heap allocated closures) so that the compacting process will update
6170 them to the closure's new location. Unfortunately these locations'
6171 @CAF@ indirections are static. This causes premature termination
6172 since the test to find the info pointer at the end of the location
6173 list will match more than one value. This can be solved by using an
6174 auxiliary dynamic array (on the top of the A stack). One location for
6175 each @CAF@ indirection is linked to the closure that the @CAF@
6176 references. Once collection is complete this array is traversed and
6177 the corresponding @CAF@ is then updated with the updated pointer from
6178 the auxiliary array.
6181 It is possible to use an alternative marking scheme, using a similar
6182 idea to the copying solution. This scheme avoids the need to update
6183 the @CAF@ references explicitly. We introduce an auxillary {\em mark
6184 and update} @CAF@ info-table which is used to update all @CAF@s at the
6185 start of a collection. The new code marks the @CAF@ reference,
6186 updating it with the returned reference. The returned reference is
6187 itself returned so the @CAF@ is shorted out. The code also modifies the
6188 @CAF@ info-table to be a {\em return reference}. Subsequent attempts to
6189 mark the @CAF@ simply return the updated reference.
6191 A cyclic @CAF@ reference will result in an attempt to mark the @CAF@
6192 before the marking has been completed and the reference updated. We
6193 cannot start marking the @CAF@ as it is already being marked. Nor can
6194 we return the reference as it has not yet been updated. Neither can we
6195 treat the CAF as an indirection since the @CAF@ reference has been
6196 obscured by the pointer reversal stack. All we can do is return the
6197 @CAF@ itself. This will result in some @CAF@ references not being
6200 This scheme has not been adopted but has been implemented. The code is
6201 commented out with @#if 0@.
6205 \subsection{The virtual register set}
6207 \ToDo{Commented out}
6211 We refer to any (atomic) part of the virtual machine state as a ``register.''
6212 These ``registers'' may be shared between all threads in the system or may be
6213 specific to each thread.
6219 Thread preemption flag
6224 TSO - pointer to the TSO for when we have to pack thread away
6227 Su - used to calculate number of arguments on stack
6228 - this is a more convenient representation
6229 Call/return registers (aka General purpose registers)
6230 Cost centre (and other debug/profile info)
6231 Statistic gathering (not in production system)
6233 Heap overflow - possible global?
6234 Stack overflow - possibly global?
6235 Pattern match failure
6236 maybe a failWith handler?
6237 maybe an exitWith handler?
6241 Some of these virtual ``registers'' are used very frequently and should
6242 be mapped onto machine registers if at all possible. Others are used
6243 very infrequently and can be kept in memory to free up registers for
6246 On register-poor architectures, we can play a few tricks to reduce the
6247 number of virtual registers which need to be accessed on a regular
6252 - Grow stack and heap towards each other (single-threaded system only)
6253 - We might need to keep the C stack pointer in a register if that
6254 is what the OS expects when a signal occurs.
6255 - Preemption flag trick
6256 - If any of the frequently accessed registers cannot be mapped onto
6257 machine registers we should keep the TSO in a machine register to
6258 allow faster access to all the other non-machine registers.