1e014e5f369f76a508e67443aa765aca2306080b
[ghc-hetmet.git] / docs / rts / rts.verb
1 %
2 % (c) The OBFUSCATION-THROUGH-GRATUITOUS-PREPROCESSOR-ABUSE Project,
3 %     Glasgow University, 1990-1994
4 %
5
6 % TODO:
7 %
8 % o I think it would be worth making the connection with CPS explicit.
9 %   Now that we have explicit activation records (on the stack), we can
10 %   explain the whole system in terms of CPS and tail calls --- with the
11 %   one requirement that we carefuly distinguish stack-allocated objects
12 %   from heap-allocated objects.
13
14
15 % \documentstyle[preprint]{acmconf}
16 \documentclass[11pt]{article}
17 \oddsidemargin 0.1 in       %   Note that \oddsidemargin = \evensidemargin
18 \evensidemargin 0.1 in
19 \marginparwidth 0.85in    %   Narrow margins require narrower marginal notes
20 \marginparsep 0 in 
21 \sloppy
22
23 \usepackage{epsfig}
24
25 \newcommand{\note}[1]{{\em Note: #1}}
26 % DIMENSION OF TEXT:
27 \textheight 8.5 in
28 \textwidth 6.25 in
29
30 \topmargin 0 in
31 \headheight 0 in
32 \headsep .25 in
33
34
35 \setlength{\parskip}{0.15cm}
36 \setlength{\parsep}{0.15cm}
37 \setlength{\topsep}{0cm}        % Reduces space before and after verbatim,
38                                 % which is implemented using trivlist 
39 \setlength{\parindent}{0cm}
40
41 \renewcommand{\textfraction}{0.2}
42 \renewcommand{\floatpagefraction}{0.7}
43
44 \begin{document}
45
46 \newcommand{\ToDo}[1]{{{\bf ToDo:}\sl #1}}
47 \newcommand{\Arg}[1]{\mbox{${\tt arg}_{#1}$}}
48 \newcommand{\bottom}{bottom} % foo, can't remember the symbol name
49
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} 
54
55 \maketitle
56
57 \tableofcontents
58 \newpage
59
60 \part{Introduction}
61 \section{Overview}
62
63 This document describes the GHC/Hugs run-time system.  It serves as 
64 a Glasgow/Yale/Nottingham ``contract'' about what the RTS does.
65
66 \subsection{New features compared to GHC 2.04}
67
68 \begin{itemize}
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
71 code.
72
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
77 space leaks.
78
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.)
85
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
89 tuples~\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.
92
93 \end{itemize} 
94
95 \subsection{Wish list}
96
97 Here's a list of things we'd like to support in the future.
98 \begin{itemize}
99 \item Interrupts, speculative computation.
100
101 \item
102 The SM could tune the size of the allocation arena, the number of
103 generations, etc taking into account residency, GC rate and page fault
104 rate.
105
106 \item
107 There should be no need to specify the amnount of stack/heap space to
108 allocate when you started a program - let it just take as much or as
109 little as it wants.  (It might be useful to be able to specify maximum
110 sizes and to be able to suggest an initial size.)
111
112 \item 
113 We could trigger a GC when all threads are blocked waiting for IO if
114 the allocation arena (or some of the generations) are nearly full.
115
116 \end{itemize}
117
118 \subsection{Configuration}
119
120 Some of the above features are expensive or less portable, so we
121 envision building a number of different configurations supporting
122 different subsets of the above features.
123
124 You can make the following choices:
125 \begin{itemize}
126 \item
127 Support for concurrency or parallelism.  There are four 
128 mutually-exclusive choices.
129
130 \begin{description}
131 \item[@SEQUENTIAL@] No concurrency or parallelism support.
132   This configuration might not support interrupt recovery.
133 \item[@CONCURRENT@]  Support for concurrency but not for parallelism.
134 \item[@CONCURRENT@+@GRANSIM@] Concurrency support and simulated parallelism.
135 \item[@CONCURRENT@+@PARALLEL@]     Concurrency support and real parallelism.
136 \end{description}
137
138 \item @PROFILING@ adds cost-centre profiling.
139
140 \item @TICKY@ gathers internal statistics (often known as ``ticky-ticky'' code).
141
142 \item @DEBUG@ does internal consistency checks.
143
144 \item Persistence. (well, not yet).
145
146 \item
147 Which garbage collector to use.  At the moment we
148 only anticipate one, however.
149 \end{itemize}
150
151 \subsection{Glossary}
152
153 \ToDo{This terminology is not used consistently within the document.
154 If you find soemthing which disagrees with this terminology, fix the
155 usage.}
156
157 \begin{itemize}
158
159 \item A {\em word} is (at least) 32 bits and can hold either a signed
160 or an unsigned int.
161
162 \item A {\em pointer} is (at least) 32 bits and big enough to hold a
163 function pointer or a data pointer.  
164
165 \item A {\em boxed} type is one whose elements are heap allocated.
166
167 \item An {\em unboxed} type is one whose elements are {\em not} heap allocated.
168
169 \item A {\em pointed} type is one that contains $\bot$.  Variables with
170 pointed types are the only things which can be lazily evaluated.  In
171 the STG machine, this means that they are the only things that can be 
172 {\em entered} or {\em updated} and it requires that they be boxed.
173
174 \item An {\em unpointed} type is one that does not contains $\bot$.
175 Variables with unpointed types are never delayed --- they are always
176 evaluated when they are constructed.  In the STG machine, this means
177 that they cannot be {\em entered} or {\em updated}.  Unpointed objects
178 may be boxed (like @Array#@) or unboxed (like @Int#@).
179
180 \item A {\em closure} is a (representation of) a value of a {\em pointed}
181 type.  It may be in HNF or it may be unevaluated --- in either case, you can
182 try to evaluate it again.
183
184 \item A {\em thunk} is a (representation of) a value of a {\em pointed}
185 type which is {\em not} in HNF.
186
187 \item A {\em value} is an object in HNF.  It can be pointed or unpointed.
188
189 \end{itemize}
190
191 Occasionally, a field of a data structure must hold either a word or a
192 pointer.  In such circumstances, it is {\em not safe} to assume that
193 words and pointers are the same size.
194
195 % Todo:
196 % More terminology to mention.
197 % unboxed, unpointed
198
199 \subsection{Invariants}
200
201 There are a few system invariants which need to be mentioned ---
202 though this is probably the wrong place for them.
203
204 \begin{itemize}
205
206 \item The garbage collector never expands an object when it promotes
207 it to the old generation.  This is important because the GC avoids
208 performing heap overflow checks by assuming that the amount added to
209 the old generation is no bigger than the current new generation.
210
211 \end{itemize}
212
213 \section{Source Language}
214
215 \subsection{Unboxed tuples}\label{sect:unboxed-tuples}
216
217 Functions can take multiple arguments as easily as they can take one
218 argument: there's no cost for adding another argument.  But functions
219 can only return one result: the cost of adding a second ``result'' is
220 that the function must construct a tuple of ``results'' on the heap.
221 The assymetry is rather galling and can make certain programming
222 styles quite expensive.  For example, consider a simple state transformer
223 monad:
224 @
225 > type S a = State -> (a,State)
226 > bindS m k s0 = case m s0 of { (a,s1) -> k a s1 }
227 > returnS a s  = (a,s)
228 > getS s       = (s,s)
229 > setS s _     = ((),s)
230 @
231 Here, every use of @returnS@, @getS@ or @setS@ constructs a new tuple
232 in the heap which is instantly taken apart (and becomes garbage) by
233 the case analysis in @bind@.  Even a short state-transformer program
234 will construct a lot of these temporary tuples.
235
236 Unboxed tuples provide a way for the programmer to indicate that they
237 do not expect a tuple to be shared and that they do not expect it to
238 be allocated in the heap.  Syntactically, unboxed tuples are just like
239 single constructor datatypes except for the annotation @unboxed@.
240 @
241 > data unboxed AAndState# a = AnS a State
242 > type S a = State -> AAndState# a
243 > bindS m k s0 = case m s0 of { AnS a s1 -> k a s1 }
244 > returnS a s  = AnS a s
245 > getS s       = AnS s s
246 > setS s _     = AnS () s
247 @
248 Semantically, unboxed tuples are just unlifted tuples and are subject
249 to the same restrictions as other unpointed types.
250
251 Operationally, unboxed tuples are never built on the heap.  When
252 unboxed tuples are returned, they are returned in multiple registers
253 or multiple stack slots.  At first sight, this seems a little strange
254 but it's no different from passing double precision floats in two
255 registers.
256
257 Note that unboxed tuples can only have one constructor and that
258 thunks never have unboxed types --- so we'll never try to update an
259 unboxed constructor.  The restriction to a single constructor is
260 largely to avoid garbage collection complications.
261
262
263 %-----------------------------------------------------------------------------
264 \part{Evaluation Model}
265 \section{Compiled Execution}
266
267 This section describes the framework in which compiled code evaluates
268 expressions.  Only at certain points will compiled code need to be
269 able to talk to the interpreted world; these are discussed in Section
270 \ref{sect:switching-worlds}.
271
272 \subsection{Calling conventions}
273
274 \subsubsection{The call/return registers}
275
276 One of the problems in designing a virtual machine is that we want it
277 abstract away from tedious machine details but still reveal enough of
278 the underlying hardware that we can make sensible decisions about code
279 generation.  A major problem area is the use of registers in
280 call/return conventions.  On a machine with lots of registers, it's
281 cheaper to pass arguments and results in registers than to pass them
282 on the stack.  On a machine with very few registers, it's cheaper to
283 pass arguments and results on the stack than to use ``virtual
284 registers'' in memory.  We therefore use a hybrid system: the first
285 $n$ arguments or results are passed in registers; and the remaining
286 arguments or results are passed on the stack.  For register-poor
287 architectures, it is important that we allow $n=0$.
288
289 We'll label the arguments and results \Arg{1} \ldots \Arg{m} --- with
290 the understanding that \Arg{1} \ldots \Arg{n} are in registers and
291 \Arg{n+1} \ldots \Arg{m} are on top of the stack.
292
293 Note that the mapping of arguments \Arg{1} \ldots \Arg{n} to machine
294 registers depends on the {\em kinds} of the arguments.  For example,
295 if the first argument is a Float, we might pass it in a different
296 register from if it is an Int.  In fact, we might find that a given
297 architecture lets us pass varying numbers of arguments according to
298 their types.  For example, if a CPU has 2 Int registers and 2 Float
299 registers then we could pass between 2 and 4 arguments in machine
300 registers --- depending on whether they all have the same kind or they
301 have different kinds.
302
303 \subsubsection{Entering closures}
304
305 To evaluate a closure we jump to the entry code for the closure
306 passing a pointer to the closure in \Arg{1} so that the entry code can
307 access its environment.
308
309 \subsubsection{Function call}
310
311 The function-call mechanism is obviously crucial.  There are five different
312 cases to consider:
313 \begin{enumerate}
314
315 \item {\em Known combinator (function with no free variables) and enough arguments.}  
316
317 A fast call can be made: push excess arguments onto stack and jump to
318 function's {\em fast entry point} passing arguments in \Arg{1} \ldots
319 \Arg{m}.  
320
321 The {\em fast entry point} is only called with exactly the right
322 number of arguments (in \Arg{1} \ldots \Arg{m}) so it can instantly
323 start doing useful work without first testing whether it has enough
324 registers or having to pop them off the stack first.
325
326 \item {\em Known combinator and insufficient arguments.}
327
328 A slow call can be made: push all arguments onto stack and jump to
329 function's {\em slow entry point}.
330
331 Any unpointed arguments which are pushed on the stack must be tagged.
332 This means pushing an extra word on the stack below the unpointed
333 words, containing the number of unpointed words above it.
334
335 %Todo: forward ref about tagging?
336 %Todo: picture?
337
338 The {\em slow entry point} might be called with insufficient arguments
339 and so it must test whether there are enough arguments on the stack.
340 This {\em argument satisfaction check} consists of checking that
341 @Su-Sp@ is big enough to hold all the arguments (including any tags).
342
343 \begin{itemize} 
344
345 \item If the argument satisfaction check fails, it is because there is
346 one or more update frames on the stack before the rest of the
347 arguments that the function needs.  In this case, we construct a PAP
348 (partial application, section~\ref{sect:PAP}) containing the arguments
349 which are on the stack.  The PAP construction code will return to the
350 update frame with the address of the PAP in \Arg{1}.
351
352 \item If the argument satisfaction check succeeds, we jump to the fast
353 entry point with the arguments in \Arg{1} \ldots \Arg{arity}.
354
355 If the fast entry point expects to receive some of \Arg{i} on the
356 stack, we can reduce the amount of movement required by making the
357 stack layout for the fast entry point look like the stack layout for
358 the slow entry point.  Since the slow entry point is entered with the
359 first argument on the top of the stack and with tags in front of any
360 unpointed arguments, this means that if \Arg{i} is unpointed, there
361 should be space below it for a tag and that the highest numbered
362 argument should be passed on the top of the stack.
363
364 We usually arrange that the fast entry point is placed immediately
365 after the slow entry point --- so we can just ``fall through'' to the
366 fast entry point without performing a jump.
367
368 \end{itemize}
369
370
371 \item {\em Known function closure (function with free variables) and enough arguments.}
372
373 A fast call can be made: push excess arguments onto stack and jump to
374 function's {\em fast entry point} passing a pointer to closure in
375 \Arg{1} and arguments in \Arg{2} \ldots \Arg{m+1}.
376
377 Like the fast entry point for a combinator, the fast entry point for a
378 closure is only called with appropriate values in \Arg{1} \ldots
379 \Arg{m+1} so we can start work straight away.  The pointer to the
380 closure is used to access the free variables of the closure.
381
382
383 \item {\em Known function closure and insufficient arguments.}
384
385 A slow call can be made: push all arguments onto stack and jump to the
386 closure's slow entry point passing a pointer to the closure in \Arg{1}.
387
388 Again, the slow entry point performs an argument satisfaction check
389 and either builds a PAP or pops the arguments off the stack into
390 \Arg{2} \ldots \Arg{m+1} and jumps to the fast entry point.
391
392
393 \item {\em Unknown function closure, thunk or constructor.}
394
395 Sometimes, the function being called is not statically identifiable.
396 Consider, for example, the @compose@ function:
397 @
398   compose f g x = f (g x)
399 @
400 Since @f@ and @g@ are passed as arguments to @compose@, the latter has
401 to make a heap call.  In a heap call the arguments are pushed onto the
402 stack, and the closure bound to the function is entered.  In the
403 example, a thunk for @(g x)@ will be allocated, (a pointer to it)
404 pushed on the stack, and the closure bound to @f@ will be
405 entered. That is, we will jump to @f@s entry point passing @f@ in
406 \Arg{1}.  If \Arg{1} is passed on the stack, it is pushed on top of
407 the thunk for @(g x)@.
408
409 The {\em entry code} for an updateable thunk (which must have arity 0)
410 pushes an update frame on the stack and starts executing the body of
411 the closure --- using \Arg{1} to access any free variables.  This is
412 described in more detail in section~\ref{sect:data-updates}.
413
414 The {\em entry code} for a non-updateable closure is just the
415 closure's slow entry point.
416
417 \end{enumerate}
418
419 In addition to the above considerations, if there are \emph{too many}
420 arguments then the extra arguments are simply pushed on the stack with
421 appropriate tags.
422
423 To summarise, a closure's standard (slow) entry point performs the following:
424 \begin{description}
425 \item[Argument satisfaction check.] (function closure only)
426 \item[Stack overflow check.]
427 \item[Heap overflow check.]
428 \item[Copy free variables out of closure.] %Todo: why?
429 \item[Eager black holing.] (updateable thunk only) %Todo: forward ref.
430 \item[Push update frame.]
431 \item[Evaluate body of closure.]
432 \end{description}
433
434
435 \subsection{Case expressions and return conventions}
436 \label{sect:return-conventions}
437
438 The {\em evaluation} of a thunk is always initiated by
439 a @case@ expression.  For example:
440 @
441   case x of (a,b) -> E
442 @
443
444 The code for a @case@ expression looks like this:
445
446 \begin{itemize}
447 \item Push the free variables of the branches on the stack (fv(@E@) in
448 this case).
449 \item  Push a \emph{return address} on the stack.
450 \item  Evaluate the scrutinee (@x@ in this case).
451 \end{itemize}
452
453 Once evaluation of the scrutinee is complete, execution resumes at the
454 return address, which points to the code for the expression @E@.
455
456 When execution resumes at the return point, there must be some {\em
457 return convention} that defines where the components of the pair, @a@
458 and @b@, can be found.  The return convention varies according to the
459 type of the scrutinee @x@:
460
461 \begin{itemize}
462
463 \item 
464
465 (A space for) the return address is left on the top of the stack.
466 Leaving the return address on the stack ensures that the top of the
467 stack contains a valid activation record
468 (section~\ref{sect:activation-records}) --- should a garbage collection
469 be required.
470
471 \item If @x@ has a boxed type (e.g.~a data constructor or a function),
472 a pointer to @x@ is returned in \Arg{1}.
473
474 \ToDo{Warn that components of E should be extracted as soon as
475 possible to avoid a space leak.}
476
477 \item If @x@ is an unboxed type (e.g.~@Int#@ or @Float#@), @x@ is
478 returned in \Arg{1}
479
480 \item If @x@ is an unboxed tuple constructor, the components of @x@
481 are returned in \Arg{1} \ldots \Arg{n} but no object is constructed in
482 the heap.  
483
484 When passing an unboxed tuple to a function, the components are
485 flattened out and passed in \Arg{1} \ldots \Arg{n} as usual.
486
487 \end{itemize}
488
489 \subsection{Vectored Returns}
490
491 Many algebraic data types have more than one constructor.  For
492 example, the @Maybe@ type is defined like this:
493 @
494   data Maybe a = Nothing | Just a
495 @
496 How does the return convention encode which of the two constructors is
497 being returned?  A @case@ expression scrutinising a value of @Maybe@
498 type would look like this: 
499 @
500   case E of 
501     Nothing -> ...
502     Just a  -> ...
503 @
504 Rather than pushing a return address before evaluating the scrutinee,
505 @E@, the @case@ expression pushes (a pointer to) a {\em return
506 vector}, a static table consisting of two code pointers: one for the
507 @Just@ alternative, and one for the @Nothing@ alternative.  
508
509 \begin{itemize}
510
511 \item
512
513 The constructor @Nothing@ returns by jumping to the first item in the
514 return vector with a pointer to a (statically built) Nothing closure
515 in \Arg{1}.  
516
517 It might seem that we could avoid loading \Arg{1} in this case since the
518 first item in the return vector will know that @Nothing@ was returned
519 (and can easily access the Nothing closure in the (unlikely) event
520 that it needs it.  The only reason we load \Arg{1} is in case we have to
521 perform an update (section~\ref{sect:data-updates}).
522
523 \item 
524
525 The constructor @Just@ returns by jumping to the second element of the
526 return vector with a pointer to the closure in \Arg{1}.  
527
528 \end{itemize}
529
530 In this way no test need be made to see which constructor returns;
531 instead, execution resumes immediately in the appropriate branch of
532 the @case@.
533
534 \subsection{Direct Returns}
535
536 When a datatype has a large number of constructors, it may be
537 inappropriate to use vectored returns.  The vector tables may be
538 large and sparse, and it may be better to identify the constructor
539 using a test-and-branch sequence on the tag.  For this reason, we
540 provide an alternative return convention, called a \emph{direct
541 return}.
542
543 In a direct return, the return address pushed on the stack really is a
544 code pointer.  The returning code loads a pointer to the closure being
545 returned in \Arg{1} as usual, and also loads the tag into \Arg{2}.
546 The code at the return address will test the tag and jump to the
547 appropriate code for the case branch.
548
549 The choice of whether to use a vectored return or a direct return is
550 made on a type-by-type basis --- up to a certain maximum number of
551 constructors imposed by the update mechanism
552 (section~\ref{sect:data-updates}).
553
554 Single-constructor data types also use direct returns, although in
555 that case there is no need to return a tag in \Arg{2}.
556
557 \ToDo{Say whether we pop the return address before returning}
558
559 \ToDo{Stack stubbing?}
560
561 \subsection{Updates}
562 \label{sect:data-updates}
563
564 The entry code for an updatable thunk (which must be of arity 0):
565
566 \begin{itemize}
567 \item copies the free variables out of the thunk into registers or
568   onto the stack.
569 \item pushes an {\em update frame} onto the stack.
570
571 An update frame is a small activation record consisting of
572 \begin{center}
573 \begin{tabular}{|l|l|l|}
574 \hline
575 {\em Fixed header} & {\em Update Frame link} & {\em Updatee} \\
576 \hline
577 \end{tabular}
578 \end{center}
579
580 \note{In the semantics part of the STG paper (section 5.6), an update
581 frame consists of everything down to the last update frame on the
582 stack.  This would make sense too --- and would fit in nicely with
583 what we're going to do when we add support for speculative
584 evaluation.}
585 \ToDo{I think update frames contain cost centres sometimes}
586
587 \item 
588 If we are doing ``eager blackholing,'' we then overwrite the thunk
589 with a black hole.  Otherwise, we leave it to the garbage collector to
590 black hole the thunk.
591
592 \item 
593 Start evaluating the body of the expression.
594
595 \end{itemize}
596
597 When the expression finishes evaluation, it will enter the update
598 frame on the top of the stack.  Since the returner doesn't know
599 whether it is entering a normal return address/vector or an update
600 frame, we follow exactly the same conventions as return addresses and
601 return vectors.  That is, on entering the update frame:
602
603 \begin{itemize} 
604 \item The value of the thunk is in \Arg{1}.  (Recall that only thunks
605 are updateable and that thunks return just one value.)
606
607 \item If the data type is a direct-return type rather than a
608 vectored-return type, then the tag is in \Arg{2}.
609
610 \item The update frame is still on the stack.
611 \end{itemize}
612
613 We can safely share a single statically-compiled update function
614 between all types.  However, the code must be able to handle both
615 vectored and direct-return datatypes.  This is done by arranging that
616 the update code looks like this:
617
618 @
619                 |       ^       |
620                 | return vector |
621                 |---------------|
622                 |  fixed-size   |
623                 |  info table   |
624                 |---------------|  <- update code pointer
625                 |  update code  |
626                 |       v       |
627 @
628
629 Each entry in the return vector (which is large enough to cover the
630 largest vectored-return type) points to the update code.
631
632 The update code:
633 \begin{itemize}
634 \item overwrites the {\em updatee} with an indirection to \Arg{1};
635 \item loads @Su@ from the Update Frame link;
636 \item removes the update frame from the stack; and 
637 \item enters \Arg{1}.
638 \end{itemize}
639
640 We enter \Arg{1} again, having probably just come from there, because
641 it knows whether to perform a direct or vectored return.  This could
642 be optimised by compiling special update code for each slot in the
643 return vector, which performs the correct return.
644
645 \subsection{Semi-tagging}
646 \label{sect:semi-tagging}
647
648 When a @case@ expression evaluates a variable that might be bound
649 to a thunk it is often the case that the scrutinee is already evaluated.
650 In this case we have paid the penalty of (a) pushing the return address (or
651 return vector address) on the stack, (b) jumping through the info pointer
652 of the scrutinee, and (c) returning by an indirect jump through the
653 return address on the stack.
654
655 If we knew that the scrutinee was already evaluated we could generate
656 (better) code which simply jumps to the appropriate branch of the
657 @case@ with a pointer to the scrutinee in \Arg{1}.  (For direct
658 returns to multiconstructor datatypes, we might also load the tag into
659 \Arg{2}).
660
661 An obvious idea, therefore, is to test dynamically whether the heap
662 closure is a value (using the tag in the info table).  If not, we
663 enter the closure as usual; if so, we jump straight to the appropriate
664 alternative.  Here, for example, is pseudo-code for the expression
665 @(case x of { (a,_,c) -> E }@:
666 @
667       \Arg{1} = <pointer to x>;
668       tag = \Arg{1}->entry->tag;
669       if (isWHNF(tag)) {
670           Sp--;  \\ insert space for return address
671           goto ret;
672       }
673       push(ret);           
674       goto \Arg{1}->entry;
675       
676       <info table for return address goes here>
677 ret:  a = \Arg{1}->data1; \\ suck out a and c to avoid space leak
678       c = \Arg{1}->data3;
679       <code for E2>
680 @
681 and here is the code for the expression @(case x of { [] -> E1; x:xs -> E2 }@:
682 @
683       \Arg{1} = <pointer to x>;
684       tag = \Arg{1}->entry->tag;
685       if (isWHNF(tag)) {
686           Sp--;  \\ insert space for return address
687           goto retvec[tag];
688       }
689       push(retinfo);          
690       goto \Arg{1}->entry;
691       
692       .addr ret2
693       .addr ret1
694 retvec:           \\ reversed return vector
695       <return info table for case goes here>
696 retinfo:
697       panic("Direct return into vectored case");
698       
699 ret1: <code for E1>
700
701 ret2: x  = \Arg{1}->head;
702       xs = \Arg{1}->tail;
703       <code for E2>
704 @
705 There is an obvious cost in compiled code size (but none in the size
706 of the bytecodes).  There is also a cost in execution time if we enter
707 more thunks than data constructors.
708
709 Both the direct and vectored returns are easily modified to chase chains
710 of indirections too.  In the vectored case, this is most easily done by
711 making sure that @IND = TAG_1 - 1@, and adding an extra field to every
712 return vector.  In the above example, the indirection code would be
713 @
714 ind:  \Arg{1} = \Arg{1}->next;
715       goto ind_loop;
716 @
717 where @ind_loop@ is the second line of code.
718
719 Note that we have to leave space for a return address since the return
720 address expects to find one.  If the body of the expression requires a
721 heap check, we will actually have to write the return address before
722 entering the garbage collector.
723
724
725 \subsection{Heap and Stack Checks}
726
727 \note{I reckon these deserve a subsection of their own}
728
729 The storage manager detects that it needs to garbage collect the old
730 generation when the evaluator requests a garbage collection without
731 having moved the heap pointer since the last garbage collection.  It
732 is therefore important that the GC routines {\em not} move the heap
733 pointer unless the heap check fails.  This is different from what
734 happens in the current STG implementation.
735
736 Talk about how stack check looks ahead into the branches of case expressions.
737
738
739 \subsection{Handling interrupts/signals}
740
741 @
742 May have to keep C stack pointer in register to placate OS?
743 May have to revert black holes - ouch!
744 @
745
746 \section{Interpreted Execution}
747
748 This section describes how the Hugs interpreter interprets code in the
749 same environment as compiled code executes.  Both evaluation models
750 use a common garbage collector, so they must agree on the form of
751 objects in the heap.
752
753 Hugs interprets code by converting it to byte-code and applying a
754 byte-code interpreter to it.  Wherever possible, we try to ensure that
755 the byte-code is all that is required to interpret a section of code.
756 This means not dynamically generating info tables, and hence we can
757 only have a small number of possible heap objects each with a staticly
758 compiled info table.  Similarly for stack objects: in fact we only
759 have one Hugs stack object, in which all information is tagged for the
760 garbage collector.
761
762 There is, however, one exception to this rule.  Hugs must generate
763 info tables for any constructors it is asked to compile, since the
764 alternative is to force a context-switch each time compiled code
765 enters a Hugs-built constructor, which would be prohibitively
766 expensive.
767
768 \subsection{Hugs Heap Objects}
769 \label{sect:hugs-heap-objects}
770
771 \subsubsection{Byte-Code Objects}
772
773 Compiled byte code lives on the global heap, in objects called
774 Byte-Code Objects (or BCOs).  The layout of BCOs is described in
775 detail in Section \ref{sect:BCO}, in this section we will describe
776 their semantics.
777
778 Since byte-code lives on the heap, it can be garbage collected just
779 like any other heap-resident data.  Hugs maintains a table of
780 currently live BCOs, which is treated as a table of live pointers by
781 the garbage collector.  When a module is unloaded, the pointers to its
782 BCOs are removed from the table, and the code will be garbage
783 collected some time later.
784
785 A BCO represents a basic block of code - all entry points are at the
786 beginning of a BCO, and it is impossible to jump into the middle of
787 one.  A BCO represents not only the code for a function, but also its
788 closure; a BCO can be entered just like any other closure.  Hugs
789 performs lambda-lifting during compilation to byte-code, and each
790 top-level combinator becomes a BCO in the heap.
791
792 \subsubsection{Thunks and partial applications}
793
794 A thunk consists of a code pointer, and values for the free variables
795 of that code.  Since Hugs byte-code is lambda-lifted, free variables
796 become arguments and are expected to be on the stack by the called
797 function.
798
799 Hugs represents thunks with an @HUGS_AP@ object.  The @HUGS_AP@ object
800 contains one or more pointers to other heap objects.  When it is
801 entered, it pushes an update frame followed by its payload on the
802 stack, and enters the first word (which will be a pointer to a BCO).
803 The layout of @HUGS_AP@ objects is described in more detail in Section
804 \ref{sect:HUGS-AP}.
805
806 Partial applications are represented by @HUGS_PAP@ objects, which are
807 identical to @HUGS_AP@s except that they are non-updatable.
808
809 \ToDo{Hugs Constructors}.
810
811 \subsection{Calling conventions}
812 \label{sect:hugs-calling-conventions}
813
814 The calling convention for any byte-code function is straightforward:
815 \begin{itemize}
816 \item Push any arguments on the stack.
817 \item Push a pointer to the BCO.
818 \item Begin interpreting the byte code.
819 \end{itemize}
820
821 But it isn't enough for the bytecode interpreter to handle just
822 byte-code functions specially.  At a minimum, it must also be able to
823 enter constructors too because of the way that GHC returns to
824 Hugs-compiled return addresses (Section~\ref{sect:ghc-to-hugs-return}).
825
826 In principle, all other closure types could be handled by switching to
827 the compiled world (as described in
828 Section~\ref{sect:hugs-to-ghc-closure}) and entering the closure
829 there.  This would work but it would obviously be very inefficient if
830 we entered a @HUGS_AP@ by switching worlds, entering the @HUGS_AP@,
831 pushing the arguments and function onto the stack, and entering the
832 function which, likely as not, will be a byte-code object which we
833 will enter by \emph{returning} to the byte-code interpreter.  To avoid
834 such gratuitious world switching, we choose to recognise certain
835 closure types as being ``standard'' --- and duplicate the entry code
836 for the ``standard closures'' in the bytecode interpreter.
837
838 A closure is said to be ``standard'' if its entry code is entirely
839 determined by its info table.  \emph{Standard Closures} have the
840 desirable property that the byte-code interpreter can enter
841 the closure by simply ``interpreting'' the info table instead of
842 switching to the compiled world.  The standard closures include:
843
844 \begin{description}
845 \item[@HUGS_AP@] 
846 To enter a @HUGS_AP@ we push an update frame, push the values from the
847 @HUGS_AP@ on the stack, and enter its associated object.
848
849 \item[@HUGS_PAP@]
850 To enter a @HUGS_PAP@, we push its values on the stack and enter the
851 first one.
852
853 \item[@PAP@]
854 Same as @HUGS_PAP@.
855
856 \item[Constructor]
857 To enter a constructor, we simply return (see Section
858 \ref{sect:hugs-return-convention}).
859
860 \item[Indirection]
861 To enter an indirection, we simply enter the object it points to
862 after possibly adjusting the current cost centre.
863
864 \item[Selector] 
865 To enter a selector, we test whether the selectee is a value.  If so,
866 we simply select the appropriate component; if not, it's simplest to
867 treat it as a GHC-built closure --- though we could interpret it if we
868 wanted.
869
870 \end{description}
871
872 The most obvious omissions from the above list are @BCO@s (which we
873 dealt with above) and GHC-built closures (which are covered in Section
874 \ref{sect:hugs-to-ghc-closure}).
875
876
877 \subsection{Return convention}
878 \label{sect:hugs-return-convention}
879
880 When Hugs pushes a return address, it pushes both a pointer to the BCO
881 to return to, and a pointer to a static code fragment @HUGS_RET@ (this
882 will be described in Section \ref{sect:ghc-to-hugs-return}).  The
883 stack layout is shown in Figure \ref{fig:hugs-return-stack}.
884
885 \begin{figure}
886 \begin{center}
887 \input{hugs_ret.pstex_t}
888 \end{center}
889 \caption{Stack layout for a Hugs return address}
890 \label{fig:hugs-return-stack}
891 \end{figure}
892
893 \begin{figure}
894 \begin{center}
895 \input{hugs_ret2.pstex_t}
896 \end{center}
897 \caption{Stack layout on enterings a Hugs return address}
898 \label{fig:hugs-return2}
899 \end{figure}
900
901 When a Hugs byte-code sequence is returning, it first places the
902 return value on the stack.  It then examines the return address (now
903 the second word on the stack):
904
905 \begin{itemize}
906
907 \item If the return address is @HUGS_RET@, rearrange the stack so that
908 it has the returned object followed by the pointer to the BCO at the
909 top, then enter the BCO (Figure \ref{fig:hugs-return2}).
910
911 \item If the top of the stack is not @HUGS_RET@, we need to do a world
912 switch as described in Section \ref{sect:hugs-to-ghc-return}.
913
914 \end{itemize}
915
916
917 \section{The Scheduler}
918
919 The Scheduler is the heart of the run-time system.  A running program
920 consists of a single running thread, and a list of runnable and
921 blocked threads.  The running thread returns to the scheduler when any
922 of the following conditions arises:
923
924 \begin{itemize}
925 \item A heap check fails, and a garbage collection is required
926 \item Compiled code needs to switch to interpreted code, and vice
927 versa.
928 \item The thread becomes blocked.
929 \item The thread is preempted.
930 \end{itemize}
931
932 A running system has a global state, consisting of
933
934 \begin{itemize}
935 \item @Hp@, the current heap pointer, which points to the next
936 available address in the Heap.
937 \item @HpLim@, the heap limit pointer, which points to the end of the
938 heap.
939 \item The Thread Preemption Flag, which is set whenever the currently
940 running thread should be preempted at the next opportunity.
941 \item A list of runnable threads. 
942 \item A list of blocked threads.
943 \end{itemize}
944
945 Each thread is represented by a Thread State Object (TSO), which is
946 described in detail in Section \ref{sect:TSO}.
947
948 The following is pseudo-code for the inner loop of the scheduler
949 itself.
950
951 @
952 while (threads_exist) {
953   // handle global problems: GC, parallelism, etc
954   if (need_gc) gc();  
955   if (external_message) service_message();
956   // deal with other urgent stuff
957
958   pick a runnable thread;
959   do {
960     switch (thread->whatNext) {
961       case (EnterGHC  pc): status=runGHC(pc);  break;
962       case (EnterHugs bc): status=runHugs(bc); break;
963     }
964     switch (status) {  // handle local problems
965       case (StackOverflow): enlargeStack; break;
966       case (Error e)      : error(thread,e); break;
967       case (ExitWith e)   : exit(e); break;
968       case (Yield)        : break;
969     }
970   } while (thread_runnable);
971 }
972 @
973
974 Optimisations to avoid excess trampolining from Hugs into itself.
975 How do we invoke GC, ccalls, etc.
976 General ccall (@ccall-GC@) and optimised ccall.
977
978 \section{Switching Worlds}
979
980 \label{sect:switching-worlds}
981
982 Because this is a combined compiled/interpreted system, the
983 interpreter will sometimes encounter compiled code, and vice-versa.
984
985 All world-switches go via the scheduler, ensuring that the world is in
986 a known state ready to enter either compiled code or the interpreter.
987 When a thread is run from the scheduler, the @whatNext@ field in the
988 TSO (Section \ref{sect:TSO}) is checked to find out how to execute the
989 thread.
990
991 \begin{itemize}
992 \item If @whatNext@ is set to @ReturnGHC@, we load up the required
993 registers from the TSO and jump to the address at the top of the user
994 stack.
995 \item If @whatNext@ is set to @EnterGHC@, we load up the required
996 registers from the TSO and enter the closure pointed to by the top
997 word of the stack.
998 \item If @whatNext@ is set to @EnterHugs@, we enter the top thing on
999 the stack, using the interpreter.
1000 \end{itemize}
1001
1002 There are four cases we need to consider:
1003
1004 \begin{enumerate}
1005 \item A GHC thread enters a Hugs-built closure.
1006 \item A GHC thread returns to a Hugs-compiled return address.
1007 \item A Hugs thread enters a GHC-built closure.
1008 \item A Hugs thread returns to a Hugs-compiled return address.
1009 \end{enumerate}
1010
1011 GHC-compiled modules cannot call functions in a Hugs-compiled module
1012 directly, because the compiler has no information about arities in the
1013 external module.  Therefore it must assume any top-level objects are
1014 CAFs, and enter their closures.
1015
1016 \ToDo{dynamic linking stuff}
1017 \ToDo{Hugs-built constructors?}
1018
1019 We now examine the various cases one by one and describe how the
1020 switch happens in each situation.
1021
1022 \subsection{A GHC thread enters a Hugs-built closure}
1023 \label{sect:ghc-to-hugs-closure}
1024
1025 There are three possibilities: GHC has entered the BCO directly (for a
1026 top-level function closure), it has entered a @HUGS_AP@, or it has
1027 entered a @HUGS_PAP@.
1028
1029 The code for all three objects is the same:
1030
1031 \begin{itemize}
1032 \item Push the address of the object entered on the stack.
1033 \item Save the current state of the thread in its TSO.
1034 \item Return to the scheduler, setting @whatNext@ to @EnterHugs@.
1035 \end{itemize}
1036
1037 \subsection{A GHC thread returns to a Hugs-compiled return address}
1038 \label{sect:ghc-to-hugs-return}
1039
1040 Hugs return addresses are laid out as in Figure
1041 \ref{fig:hugs-return-stack}.  If GHC is returning, it will return to
1042 the address at the top of the stack, namely @HUGS_RET@.  The code at
1043 @HUGS_RET@ performs the following:
1044
1045 \begin{itemize}
1046 \item pushes \Arg{1} (the return value) on the stack.
1047 \item saves the thread state in the TSO
1048 \item returns to the scheduler with @whatNext@ set to @EnterHugs@.
1049 \end{itemize}
1050
1051 \noindent When Hugs runs, it will enter the return value, which will
1052 return using the correct Hugs convention (Section
1053 \ref{sect:hugs-return-convention}) to the return address underneath it
1054 on the stack.
1055
1056 \subsection{A Hugs thread enters a GHC-compiled closure}
1057 \label{sect:hugs-to-ghc-closure}
1058
1059 Hugs can recognise a GHC-built closure as not being one of the
1060 following types of object:
1061
1062 \begin{itemize}
1063 \item A @BCO@,
1064 \item A @HUGS_AP@,
1065 \item A @HUGS_PAP@,
1066 \item An indirection, or
1067 \item A constructor.
1068 \end{itemize}
1069
1070 When Hugs is called on to enter a GHC closure, it executes the
1071 following sequence of instructions:
1072
1073 \begin{itemize}
1074 \item Push the address of the closure on the stack.
1075 \item Save the current state of the thread in the TSO.
1076 \item Return to the scheduler, with the @whatNext@ field set to
1077 @EnterGHC@.
1078 \end{itemize}
1079
1080 \subsection{A Hugs thread returns to a GHC-compiled return address}
1081 \label{sect:hugs-to-ghc-return}
1082
1083 When hugs encounters a return address on the stack that is not
1084 @HUGS_RET@, it knows that a world-switch is required.  At this point
1085 the stack contains a pointer to the return value, followed by the GHC
1086 return address.  The following sequence is then performed:
1087
1088 \begin{itemize}
1089 \item save the state of the thread in the TSO.
1090 \item return to the scheduler, setting @whatNext@ to @EnterGHC@.
1091 \end{itemize}
1092
1093 The first thing that GHC will do is enter the object on the top of the
1094 stack, which is a pointer to the return value.  This value will then
1095 return itself to the return address using the GHC return convention.
1096
1097 \part{Implementation}
1098 \section{Heap objects}
1099 \label{sect:fixed-header}
1100
1101 \ToDo{Fix this picture}
1102
1103 \begin{figure}
1104 \begin{center}
1105 \input{closure}
1106 \end{center}
1107 \caption{A closure}
1108 \label{fig:closure}
1109 \end{figure}
1110
1111 Every {\em heap object} is a contiguous block
1112 of memory, consisting of a fixed-format {\em header} followed
1113 by zero or more {\em data words}.
1114
1115 \ToDo{I absolutely do not believe that every heap object has a header
1116 like this - ADR.  I believe that they all have an info pointer but I
1117 see no readon why stack objects and unpointed heap objects would have
1118 an entry count since this will always be zero.}
1119
1120 The header consists of the following fields:
1121 \begin{itemize}
1122 \item A one-word {\em info pointer}, which points to
1123 the object's static {\em info table}.
1124 \item Zero or more {\em admin words} that support
1125 \begin{itemize}
1126 \item Profiling (notably a {\em cost centre} word).
1127   \note{We could possibly omit the cost centre word from some 
1128   administrative objects.}
1129 \item Parallelism (e.g. GranSim keeps the object's global address here,
1130 though GUM keeps a separate hash table).
1131 \item Statistics (e.g. a word to track how many times a thunk is entered.).
1132
1133 We add a Ticky word to the fixed-header part of closures.  This is
1134 used to indicate if a closure has been updated but not yet entered. It
1135 is set when the closure is updated and cleared when subsequently
1136 entered.
1137
1138 NB: It is {\em not} an ``entry count'', it is an
1139 ``entries-after-update count.''  The commoning up of @CONST@,
1140 @CHARLIKE@ and @INTLIKE@ closures is turned off(?) if this is
1141 required. This has only been done for 2s collection.
1142
1143 \end{itemize}
1144 \end{itemize}
1145
1146 Most of the RTS is completely insensitive to the number of admin words.
1147 The total size of the fixed header is @FIXED_HS@.
1148
1149 Many heap objects contain fields allowing them to be inserted onto lists
1150 during evaluation or during garbage collection. The lists required by
1151 the evaluator and storage manager are as follows.
1152
1153 \begin{itemize}
1154 \item 2 lists of threads: runnable threads and sleeping threads.
1155
1156 \item The {\em static object list} is a list of all statically
1157 allocated objects which might contain pointers into the heap.
1158 (Section~\ref{sect:static-objects}.)
1159
1160 \item The {\em updated thunk list} is a list of all thunks in the old
1161 generation which have been updated with an indirection.  
1162 (Section~\ref{sect:IND_OLDGEN}.)
1163
1164 \item The {\em mutables list} is a list of all other objects in the
1165 old generation which might contain pointers into the new generation.
1166 Most of the object on this list are ``mutable.''
1167 (Section~\ref{sect:mutables}.)
1168
1169 \item The {\em Foreign Object list} is a list of all foreign objects
1170  which have not yet been deallocated. (Section~\ref{sect:FOREIGN}.)
1171
1172 \item The {\em Spark pool} is a doubly(?) linked list of Spark objects
1173 maintained by the parallel system.  (Section~\ref{sect:SPARK}.)
1174
1175 \item The {\em Blocked Fetch list} (or
1176 lists?). (Section~\ref{sect:BLOCKED_FETCH}.)
1177
1178 \item For each thread, there is a list of all update frames on the
1179 stack.  (Section~\ref{sect:data-updates}.)
1180
1181
1182 \end{itemize}
1183
1184 \ToDo{The links for these fields are usually inserted immediately
1185 after the fixed header except ...}
1186
1187 \subsection{Info Tables}
1188
1189 An {\em info table} is a contiguous block of memory, {\em laid out
1190 backwards}.  That is, the first field in the list that follows
1191 occupies the highest memory address, and the successive fields occupy
1192 successive decreasing memory addresses.
1193
1194 \begin{center}
1195 \begin{tabular}{|c|}
1196    \hline Parallelism Info 
1197 \\ \hline Profile Info 
1198 \\ \hline Debug Info 
1199 \\ \hline Tag / Static reference table
1200 \\ \hline Storage manager layout info
1201 \\ \hline Closure type 
1202 \\ \hline entry code
1203 \\       \vdots
1204 \end{tabular}
1205 \end{center}
1206 An info table has the following contents (working backwards in memory
1207 addresses):
1208 \begin{itemize}
1209 \item The {\em entry code} for the closure.
1210 This code appears literally as the (large) last entry in the
1211 info table, immediately preceded by the rest of the info table.
1212 An {\em info pointer} always points to the first byte of the entry code.
1213
1214 \item A one-word {\em closure type field}, @INFO_TYPE@, identifies what kind
1215 of closure the object is.  The various types of closure are described
1216 in Section~\ref{sect:closures}.
1217 In some configurations, some useful properties of 
1218 closures (is it a HNF?  can it be sparked?)
1219 are represented as high-order bits so they can be tested quickly.
1220
1221 \item A single pointer or word --- the {\em storage manager info field},
1222 @INFO_SM@, contains auxiliary information describing the closure's
1223 precise layout, for the benefit of the garbage collector and the code
1224 that stuffs graph into packets for transmission over the network.
1225
1226 \item A one-word {\em Tag/Static Reference Table} field, @INFO_SRT@.
1227 For data constructors, this field contains the constructor tag, in the
1228 range $0..n-1$ where $n$ is the number of constructors.  For all other
1229 objects it contains a pointer to a table which enables the garbage
1230 collector to identify all accessible code and CAFs.  They are fully
1231 described in Section~\ref{sect:srt}.
1232
1233 \item {\em Profiling info\/}
1234
1235 Closure category records are attached to the info table of the
1236 closure. They are declared with the info table. We put pointers to
1237 these ClCat things in info tables.  We need these ClCat things because
1238 they are mutable, whereas info tables are immutable.  Hashing will map
1239 similar categories to the same hash value allowing statistics to be
1240 grouped by closure category.
1241
1242 Cost Centres and Closure Categories are hashed to provide indexes
1243 against which arbitrary information can be stored. These indexes are
1244 memoised in the appropriate cost centre or category record and
1245 subsequent hashes avoided by the index routine (it simply returns the
1246 memoised index).
1247
1248 There are different features which can be hashed allowing information
1249 to be stored for different groupings. Cost centres have the cost
1250 centre recorded (using the pointer), module and group. Closure
1251 categories have the closure description and the type
1252 description. Records with the same feature will be hashed to the same
1253 index value.
1254
1255 The initialisation routines, @init_index_<feature>@, allocate a hash
1256 table in which the cost centre / category records are stored. The
1257 lower bound for the table size is taken from @max_<feature>_no@. They
1258 return the actual table size used (the next power of 2). Unused
1259 locations in the hash table are indicated by a 0 entry. Successive
1260 @init_index_<feature>@ calls just return the actual table size.
1261
1262 Calls to @index_<feature>@ will insert the cost centre / category
1263 record in the @<feature>@ hash table, if not already inserted. The hash
1264 index is memoised in the record and returned. 
1265
1266 CURRENTLY ONLY ONE MEMOISATION SLOT IS AVILABLE IN EACH RECORD SO
1267 HASHING CAN ONLY BE DONE ON ONE FEATURE FOR EACH RECORD. This can be
1268 easily relaxed at the expense of extra memoisation space or continued
1269 rehashing.
1270
1271 The initialisation routines must be called before initialisation of
1272 the stacks and heap as they require to allocate storage. It is also
1273 expected that the caller may want to allocate additional storage in
1274 which to store profiling information based on the return table size
1275 value(s).
1276
1277 \begin{center}
1278 \begin{tabular}{|l|}
1279    \hline Hash Index
1280 \\ \hline Selected
1281 \\ \hline Kind
1282 \\ \hline Description String
1283 \\ \hline Type String
1284 \\ \hline
1285 \end{tabular}
1286 \end{center}
1287
1288 \begin{description}
1289 \item[Hash Index] Memoised copy
1290 \item[Selected] 
1291   Is this category selected (-1 == not memoised, selected? 0 or 1)
1292 \item[Kind]
1293 One of the following values (defined in CostCentre.lh):
1294
1295 \begin{description}
1296 \item[@CON_K@]
1297 A constructor.
1298 \item[@FN_K@]
1299 A literal function.
1300 \item[@PAP_K@]
1301 A partial application.
1302 \item[@THK_K@]
1303 A thunk, or suspension.
1304 \item[@BH_K@]
1305 A black hole.
1306 \item[@ARR_K@]
1307 An array.
1308 \item[@ForeignObj_K@]
1309 A Foreign object (non-Haskell heap resident).
1310 \item[@SPT_K@]
1311 The Stable Pointer table.  (There should only be one of these but it
1312 represents a form of weak space leak since it can't shrink to meet
1313 non-demand so it may be worth watching separately? ADR)
1314 \item[@INTERNAL_KIND@]
1315 Something internal to the runtime system.
1316 \end{description}
1317
1318
1319 \item[Description] Source derived string detailing closure description.
1320 \item[Type] Source derived string detailing closure type.
1321 \end{description}
1322
1323 \item {\em Parallelism info\/}
1324 \ToDo{}
1325
1326 \item {\em Debugging info\/}
1327 \ToDo{}
1328
1329 \end{itemize}
1330
1331
1332 %-----------------------------------------------------------------------------
1333 \subsection{Kinds of Heap Object}
1334 \label{sect:closures}
1335
1336 Heap objects can be classified in several ways, but one useful one is
1337 this:
1338 \begin{itemize}
1339 \item 
1340 {\em Static closures} occupy fixed, statically-allocated memory
1341 locations, with globally known addresses.
1342
1343 \item 
1344 {\em Dynamic closures} are individually allocated in the heap.
1345
1346 \item 
1347 {\em Stack closures} are closures allocated within a thread's stack
1348 (which is itself a heap object).  Unlike other closures, there are
1349 never any pointers to stack closures.  Stack closures are discussed in
1350 Section~\ref{sect:stacks}.
1351
1352 \end{itemize}
1353 A second useful classification is this:
1354 \begin{itemize}
1355 \item 
1356 {\em Executive objects}, such as thunks and data constructors,
1357 participate directly in a program's execution.  They can be subdivided into
1358 three kinds of objects according to their type:
1359 \begin{itemize}
1360 \item 
1361 {\em Pointed objects}, represent values of a {\em pointed} type
1362 (<.pointed types launchbury.>) --i.e.~a type that includes $\bottom$ such as @Int@ or @Int# -> Int#@.
1363
1364 \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#@.
1365
1366 \item {\em Activation frames}, represent ``continuations''.  They are
1367 always stored on the stack and are never pointed to by heap objects or
1368 passed as arguments.  \note{It's not clear if this will still be true
1369 once we support speculative evaluation.}
1370
1371 \end{itemize}
1372
1373 \item {\em Administrative objects}, such as stack objects and thread
1374 state objects, do not represent values in the original program.
1375 \end{itemize}
1376
1377 Only pointed objects can be entered.  All pointed objects share a
1378 common header format: the ``pointed header''; while all unpointed
1379 objects share a common header format: the ``unpointed header''.
1380 \ToDo{Describe the difference and update the diagrams to mention
1381 an appropriate header type.}
1382
1383 This section enumerates all the kinds of heap objects in the system.
1384 Each is identified by a distinct @INFO_TYPE@ tag in its info table.
1385
1386 \ToDo{Check this table very carefully}
1387
1388 \begin{tabular}{|l|l|l|l|l|l|l|l|l|l|l|}
1389 \hline
1390
1391 closure kind          & HNF & UPD & NS & STA & THU & MUT & UPT & BH & IND & Section \\
1392
1393 \hline                                                              
1394 {\em Pointed} \\ 
1395 \hline 
1396
1397 @CONSTR@              & 1 &   & 1 &   &   &   &   &   &   & \ref{sect:CONSTR}    \\
1398 @CONSTR_STATIC@       & 1 &   & 1 & 1 &   &   &   &   &   & \ref{sect:CONSTR}    \\
1399 @CONSTR_STATIC_NOCAF@ & 1 &   & 1 & 1 &   &   &   &   &   & \ref{sect:CONSTR}    \\
1400
1401 @FUN@                 & 1 &   & ? &   &   &   &   &   &   & \ref{sect:FUN}       \\
1402 @FUN_STATIC@          & 1 &   & ? & 1 &   &   &   &   &   & \ref{sect:FUN}       \\
1403
1404 @THUNK@               &   & 1 &   &   & 1 &   &   &   &   & \ref{sect:THUNK}     \\
1405 @THUNK_STATIC@        &   & 1 &   & 1 & 1 &   &   &   &   & \ref{sect:THUNK}     \\
1406 @THUNK_SELECTOR@      &   & 1 & 1 &   & 1 &   &   &   &   & \ref{sect:THUNK_SEL} \\
1407
1408 @BCO@                 & 1 &   & 1 &   &   &   &   &   &   & \ref{sect:BCO}       \\
1409 @BCO_CAF@             &   & 1 &   &   & 1 &   &   &   &   & \ref{sect:BCO}       \\
1410
1411 @HUGS_AP@             &   & 1 &   &   & 1 &   &   &   &   & \ref{sect:HUGS-AP}   \\
1412 @HUGS_PAP@            &   &   & 1 &   &   &   &   &   &   & \ref{sect:HUGS-AP}   \\
1413
1414 @PAP@                 & 1 &   & 1 &   &   &   &   &   &   & \ref{sect:PAP}       \\
1415
1416 @IND@                 & ? &   & ? &   & ? &   &   &   & 1 & \ref{sect:IND}       \\
1417 @IND_OLDGEN@          & ? &   & ? &   & ? &   &   &   & 1 & \ref{sect:IND}       \\
1418 @IND_PERM@            & ? &   & ? &   & ? &   &   &   & 1 & \ref{sect:IND}       \\
1419 @IND_OLDGEN_PERM@     & ? &   & ? &   & ? &   &   &   & 1 & \ref{sect:IND}       \\
1420 @IND_STATIC@          & ? &   & ? & 1 & ? &   &   &   & 1 & \ref{sect:IND}       \\
1421                                                          
1422 \hline                                                   
1423 {\em Unpointed} \\                                       
1424 \hline                                                   
1425                                                          
1426                                                          
1427 @ARR_WORDS@           & 1 &   & 1 &   &   &   & 1 &   &   & \ref{sect:ARR_WORDS1},\ref{sect:ARR_WORDS2} \\
1428 @ARR_PTRS@            & 1 &   & 1 &   &   &   & 1 &   &   & \ref{sect:ARR_PTRS}  \\
1429 @MUTVAR@              & 1 &   & 1 &   &   & 1 & 1 &   &   & \ref{sect:MUTVAR}    \\
1430 @MUTARR_PTRS@         & 1 &   & 1 &   &   & 1 & 1 &   &   & \ref{sect:MUTARR_PTRS} \\
1431 @MUTARR_PTRS_FROZEN@  & 1 &   & 1 &   &   & 1 & 1 &   &   & \ref{sect:MUTARR_PTRS_FROZEN} \\
1432                                                          
1433 @FOREIGN@             & 1 &   & 1 &   &   &   & 1 &   &   & \ref{sect:FOREIGN}   \\
1434                                                          
1435 @BH@                  &   & 1 & 1 &   & ? & ? &   & 1 & ? & \ref{sect:BH}        \\
1436 @MVAR@                & 1 &   & 1 &   &   &   &   &   &   & \ref{sect:MVAR}      \\
1437 @IVAR@                & 1 &   & 1 &   &   &   &   &   &   & \ref{sect:IVAR}      \\
1438 @FETCHME@             & 1 &   & 1 &   &   &   &   &   &   & \ref{sect:FETCHME}   \\
1439 \hline
1440 \end{tabular}
1441
1442 Activation frames do not live (directly) on the heap --- but they have
1443 a similar organisation.  The classification bits are all zero in
1444 activation frames.
1445
1446 \begin{tabular}{|l|l|}\hline
1447 closure kind            & Section                       \\ \hline
1448 @RET_SMALL@             & \ref{sect:activation-records} \\
1449 @RET_VEC_SMALL@         & \ref{sect:activation-records} \\
1450 @RET_BIG@               & \ref{sect:activation-records} \\
1451 @RET_VEC_BIG@           & \ref{sect:activation-records} \\
1452 @UPDATE_FRAME@          & \ref{sect:activation-records} \\
1453 \hline
1454 \end{tabular}
1455
1456 There are also a number of administrative objects.  The classification bits are
1457 all zero in administrative objects.
1458
1459 \begin{tabular}{|l|l|}\hline
1460 closure kind            & Section                       \\ \hline
1461 @TSO@                   & \ref{sect:TSO}                \\
1462 @STACK_OBJECT@          & \ref{sect:STACK_OBJECT}       \\
1463 @STABLEPTR_TABLE@       & \ref{sect:STABLEPTR_TABLE}    \\
1464 @SPARK_OBJECT@          & \ref{sect:SPARK}              \\
1465 @BLOCKED_FETCH@         & \ref{sect:BLOCKED_FETCH}      \\
1466 \hline
1467 \end{tabular}
1468
1469 \ToDo{I guess the parallel system has something like a stable ptr
1470 table.  Is there any opportunity for sharing code/data structures
1471 here?}
1472
1473
1474 \subsection{Classification bits}
1475
1476 The top bits of the @INFO_TYPE@ tag tells what sort of animal the
1477 closure is.
1478
1479 \begin{tabular}{|l|l|l|}                                                        \hline
1480 Abbrev & Bit & Interpretation                                                   \\ \hline
1481 HNF    & 0   & 1 $\Rightarrow$ Head normal form                                 \\
1482 UPD    & 4   & 1 $\Rightarrow$ May be updated (inconsistent with being a HNF)   \\ 
1483 NS     & 1   & 1 $\Rightarrow$ Don't spark me  (Any HNF will have this set to 1)\\
1484 STA    & 2   & 1 $\Rightarrow$ This is a static closure                         \\
1485 THU    & 8   & 1 $\Rightarrow$ Is a thunk                                       \\
1486 MUT    & 3   & 1 $\Rightarrow$ Has mutable pointer fields                       \\ 
1487 UPT    & 5   & 1 $\Rightarrow$ Has an unpointed type (eg a primitive array)     \\
1488 BH     & 6   & 1 $\Rightarrow$ Is a black hole                                  \\
1489 IND    & 7   & 1 $\Rightarrow$ Is an indirection                                \\
1490 \hline
1491 \end{tabular}
1492
1493 Updatable structures (@_UP@) are thunks that may be shared.  Primitive
1494 arrays (@_BM@ -- Big Mothers) are structures that are always held
1495 in-memory (basically extensions of a closure).  Because there may be
1496 offsets into these arrays, a primitive array cannot be handled as a
1497 FetchMe in the parallel system, but must be shipped in its entirety if
1498 its parent closure is shipped.
1499
1500 The other bits in the info-type field simply give a unique bit-pattern
1501 to identify the closure type.
1502
1503 \iffalse
1504 @
1505 #define _NF                     0x0001  /* Normal form  */
1506 #define _NS                     0x0002  /* Don't spark  */
1507 #define _ST                     0x0004  /* Is static    */
1508 #define _MU                     0x0008  /* Is mutable   */
1509 #define _UP                     0x0010  /* Is updatable (but not mutable) */
1510 #define _BM                     0x0020  /* Is a "primitive" array */
1511 #define _BH                     0x0040  /* Is a black hole */
1512 #define _IN                     0x0080  /* Is an indirection */
1513 #define _TH                     0x0100  /* Is a thunk */
1514
1515
1516
1517 SPEC    
1518 SPEC_N          SPEC | _NF | _NS
1519 SPEC_S          SPEC | _TH
1520 SPEC_U          SPEC | _UP | _TH
1521                 
1522 GEN     
1523 GEN_N           GEN | _NF | _NS
1524 GEN_S           GEN | _TH
1525 GEN_U           GEN | _UP | _TH
1526                 
1527 DYN             _NF | _NS
1528 TUPLE           _NF | _NS | _BM
1529 DATA            _NF | _NS | _BM
1530 MUTUPLE         _NF | _NS | _MU | _BM
1531 IMMUTUPLE       _NF | _NS | _BM
1532 STATIC          _NS | _ST
1533 CONST           _NF | _NS
1534 CHARLIKE        _NF | _NS
1535 INTLIKE         _NF | _NS
1536
1537 BH              _NS | _BH
1538 BH_N            BH
1539 BH_U            BH | _UP
1540                 
1541 BQ              _NS | _MU | _BH
1542 IND             _NS | _IN
1543 CAF             _NF | _NS | _ST | _IN
1544
1545 FM              
1546 FETCHME         FM | _MU
1547 FMBQ            FM | _MU | _BH
1548
1549 TSO             _MU
1550
1551 STKO    
1552 STKO_DYNAMIC    STKO | _MU
1553 STKO_STATIC     STKO | _ST
1554                 
1555 SPEC_RBH        _NS | _MU | _BH
1556 GEN_RBH         _NS | _MU | _BH
1557 BF              _NS | _MU | _BH
1558 INTERNAL        
1559
1560 @
1561 \fi
1562
1563 Notes:
1564
1565 An indirection either points to HNF (post update); or is result of
1566 overwriting a FetchMe, in which case the thing fetched is either
1567 under evaluation (BH), or by now an HNF.  Thus, indirections get NoSpark flag.
1568
1569
1570
1571 \subsection{Hugs Objects}
1572
1573 \subsubsection{Byte-Code Objects}
1574 \label{sect:BCO}
1575
1576 A Byte-Code Object (BCO) is a container for a a chunk of byte-code,
1577 which can be executed by Hugs.  The byte-code represents a
1578 supercombinator in the program: when hugs compiles a module, it
1579 performs lambda lifting and each resulting supercombinator becomes a
1580 byte-code object in the heap.
1581
1582 There are two kinds of BCO: a standard @BCO@ which has an arity of one
1583 or more, and a @BCO_CAF@ which takes no arguments and can be updated.
1584 When a @BCO_CAF@ is updated, the code is thrown away!
1585
1586 The semantics of BCOs are described in Section
1587 \ref{sect:hugs-heap-objects}.  A BCO has the following structure:
1588
1589 \begin{center}
1590 \begin{tabular}{|l|l|l|l|l|l|}
1591 \hline 
1592 \emph{Fixed Header} & \emph{Layout} & \emph{Offset} & \emph{Size} &
1593 \emph{Literals} & \emph{Byte code} \\
1594 \hline
1595 \end{tabular}
1596 \end{center}
1597
1598 \noindent where:
1599 \begin{itemize}
1600 \item The entry code is a static code fragment/info table that
1601 returns to the scheduler to invoke Hugs (Section
1602 \ref{sect:ghc-to-hugs-closure}).
1603 \item \emph{Layout} contains the number of pointer literals in the
1604 \emph{Literals} field.
1605 \item \emph{Offset} is the offset to the byte code from the start of
1606 the object.
1607 \item \emph{Size} is the number of words of byte code in the object.
1608 \item \emph{Literals} contains any pointer and non-pointer literals used in
1609 the byte-codes (including jump addresses), pointers first.
1610 \item \emph{Byte code} contains \emph{Size} words of non-pointer byte
1611 code.
1612 \end{itemize}
1613
1614 \subsubsection{@HUGS_AP@ objects}
1615 \label{sect:HUGS-AP}
1616
1617 There are two kinds of @HUGS_AP@ objects: a standard @HUGS_AP@, used
1618 to represent thunks buit by Hugs, and a @HUGS_PAP@, used for partial
1619 applications.  The only difference between the two is that a
1620 @HUGS_PAP@ is non-updatable.
1621
1622 \begin{center}
1623 \begin{tabular}{|l|l|l|l|}
1624 \hline
1625 \emph{Fixed Header} & \emph{BCO} & \emph{Layout} & \emph{Free Variables} \\
1626 \hline
1627 \end{tabular}
1628 \end{center}
1629
1630 \noindent where:
1631
1632 \begin{itemize}
1633
1634 \item The entry code is a statically-compiled code fragment/info table
1635 that returns to the scheduler to invoke Hugs (Sections
1636 \ref{sect:ghc-to-hugs-closure}, \ref{sect:ghc-to-hugs-return}).
1637
1638 \item \emph{BCO} is a pointer to the BCO for the thunk.
1639
1640 \item \emph{Layout} contains the number of pointers and the size of
1641 the \emph{Free Variables} field.
1642
1643 \item \emph{Free Variables} contains the free variables of the
1644 thunk/partial application/return address, pointers first.
1645
1646 \end{itemize}
1647
1648 \subsection{Pointed Objects}
1649
1650 All pointed objects can be entered.
1651
1652 \subsubsection{Function closures}\label{sect:FUN}
1653
1654 Function closures represent lambda abstractions.  For example,
1655 consider the top-level declaration:
1656 @
1657   f = \x -> let g = \y -> x+y
1658             in g x
1659 @
1660 Both @f@ and @g@ are represented by function closures.  The closure
1661 for @f@ is {\em static} while that for @g@ is {\em dynamic}.
1662
1663 The layout of a function closure is as follows:
1664 \begin{center}
1665 \begin{tabular}{|l|l|l|l|}\hline
1666 {\em Fixed header}  & {\em Pointers} & {\em Non-pointers} \\ \hline
1667 \end{tabular}
1668 \end{center}
1669 The data words (pointers and non-pointers) are the free variables of
1670 the function closure.  
1671 The number of pointers
1672 and number of non-pointers are stored in the @INFO_SM@ word, in the least significant
1673 and most significant half-word respectively.
1674
1675 There are several different sorts of function closure, distinguished
1676 by their @INFO_TYPE@ field:
1677 \begin{itemize}
1678 \item @FUN@: a vanilla, dynamically allocated on the heap. 
1679
1680 \item $@FUN_@p@_@np$: to speed up garbage collection a number of
1681 specialised forms of @FUN@ are provided, for particular $(p,np)$ pairs,
1682 where $p$ is the number of pointers and $np$ the number of non-pointers.
1683
1684 \item @FUN_STATIC@.  Top-level, static, function closures (such as
1685 @f@ above) have a different
1686 layout than dynamic ones:
1687 \begin{center}
1688 \begin{tabular}{|l|l|l|}\hline
1689 {\em Fixed header}  & {\em Static object link} \\ \hline
1690 \end{tabular}
1691 \end{center}
1692 Static function closures have no free variables.  (However they may refer to other 
1693 static closures; these references are recorded in the function closure's SRT.)
1694 They have one field that is not present in dynamic closures, the {\em static object
1695 link} field.  This is used by the garbage collector in the same way that to-space
1696 is, to gather closures that have been determined to be live but that have not yet
1697 been scavenged.
1698 \note{Static function closures that have no static references, and hence
1699 a null SRT pointer, don't need the static object link field.  Is it worth
1700 taking advantage of this?  See @CONSTR_STATIC_NOCAF@.}
1701 \end{itemize}
1702
1703 Each lambda abstraction, $f$, in the STG program has its own private info table.
1704 The following labels are relevant:
1705 \begin{itemize}
1706 \item $f$@_info@  is $f$'s info table.
1707 \item $f$@_entry@ is $f$'s slow entry point (i.e. the entry code of its
1708 info table; so it will label the same byte as $f$@_info@).
1709 \item $f@_fast_@k$ is $f$'s fast entry point.  $k$ is the number of arguments
1710 $f$ takes; encoding this number in the fast-entry label occasionally catches some nasty
1711 code-generation errors.
1712 \end{itemize}
1713
1714 \subsubsection{Data Constructors}\label{sect:CONSTR}
1715
1716 Data-constructor closures represent values constructed with
1717 algebraic data type constructors.
1718 The general layout of data constructors is the same as that for function
1719 closures.  That is
1720 \begin{center}
1721 \begin{tabular}{|l|l|l|l|}\hline
1722 {\em Fixed header}  & {\em Pointers} & {\em Non-pointers} \\ \hline
1723 \end{tabular}
1724 \end{center}
1725
1726 The SRT pointer in a data constructor's info table is used for the
1727 constructor tag, since a constructor never has any static references.
1728
1729 There are several different sorts of constructor:
1730 \begin{itemize}
1731 \item @CONSTR@: a vanilla, dynamically allocated constructor.
1732 \item @CONSTR_@$p$@_@$np$: just like $@FUN_@p@_@np$.
1733 \item @CONSTR_INTLIKE@.
1734 A dynamically-allocated heap object that looks just like an @Int@.  The 
1735 garbage collector checks to see if it can common it up with one of a fixed
1736 set of static int-like closures, thus getting it out of the dynamic heap
1737 altogether.
1738
1739 \item @CONSTR_CHARLIKE@:  same deal, but for @Char@.
1740
1741 \item @CONSTR_STATIC@ is similar to @FUN_STATIC@, with the complication that
1742 the layout of the constructor must mimic that of a dynamic constructor,
1743 because a static constructor might be returned to some code that unpacks it.
1744 So its layout is like this:
1745 \begin{center}
1746 \begin{tabular}{|l|l|l|l|l|}\hline
1747 {\em Fixed header}  & {\em Pointers} & {\em Non-pointers} & {\em Static object link}\\ \hline
1748 \end{tabular}
1749 \end{center}
1750 The static object link, at the end of the closure, serves the same purpose
1751 as that for @FUN_STATIC@.  The pointers in the static constructor can point
1752 only to other static closures.
1753
1754 The static object link occurs last in the closure so that static
1755 constructors can store their data fields in exactly the same place as
1756 dynamic constructors.
1757
1758 \item @CONSTR_STATIC_NOCAF@.  A statically allocated data constructor
1759 that guarantees not to point (directly or indirectly) to any CAF
1760 (section~\ref{sect:CAF}).  This means it does not need a static object
1761 link field.  Since we expect that there might be quite a lot of static
1762 constructors this optimisation makes sense.  Furthermore, the @NOCAF@
1763 tag allows the compiler to indicate that no CAFs can be reached
1764 anywhere {\em even indirectly}.
1765
1766
1767 \end{itemize}
1768
1769 For each data constructor $Con$, two
1770 info tables are generated:
1771 \begin{itemize}
1772 \item $Con$@_info@ labels $Con$'s dynamic info table, 
1773 shared by all dynamic instances of the constructor.
1774 \item $Con$@_static@ labels $Con$'s static info table, 
1775 shared by all static instances of the constructor.
1776 \end{itemize}
1777
1778 \subsubsection{Thunks}
1779 \label{sect:THUNK}
1780 \label{sect:THUNK_SEL}
1781
1782 A thunk represents an expression that is not obviously in head normal 
1783 form.  For example, consider the following top-level definitions:
1784 @
1785   range = between 1 10
1786   f = \x -> let ys = take x range
1787             in sum ys
1788 @
1789 Here the right-hand sides of @range@ and @ys@ are both thunks; the former
1790 is static while the latter is dynamic.
1791
1792 The layout of a thunk is the same as that for a function closure,
1793 except that it may have some words of ``slop'' at the end to make sure
1794 that it has 
1795 at least @MIN_UPD_PAYLOAD@ words in addition to its
1796 fixed header.
1797 \begin{center}
1798 \begin{tabular}{|l|l|l|l|l|}\hline
1799 {\em Fixed header}  & {\em Pointers} & {\em Non-pointers} & {\em Slop} \\ \hline
1800 \end{tabular}
1801 \end{center}
1802 The @INFO_SM@ word contains the same information as for function
1803 closures; that is, number of pointers and number of non-pointers (excluding slop).
1804
1805 A thunk differs from a function closure in that it can be updated.
1806
1807 There are several forms of thunk:
1808 \begin{itemize}
1809 \item @THUNK@: a vanilla, dynamically allocated thunk.
1810 The garbage collection code for thunks whose
1811 pointer + non-pointer words is less than @MIN_UPD_PAYLOAD@ differs from
1812 that for function closures and data constructors, because the GC code
1813 has to account for the slop.
1814 \item $@THUNK_@p@_@np$.  Similar comments apply.
1815 \item @THUNK_STATIC@.  A static thunk is also known as 
1816 a {\em constant applicative form}, or {\em CAF}.
1817
1818 \begin{center}
1819 \begin{tabular}{|l|l|l|l|l|}\hline
1820 {\em Fixed header}  & {\em Pointers} & {\em Non-pointers} & {\em Slop} & {\em Static object link}\\ \hline
1821 \end{tabular}
1822 \end{center}
1823
1824 \item @THUNK_SELECTOR@ is a (dynamically allocated) thunk
1825 whose entry code performs a simple selection operation from
1826 a data constructor drawn from a single-constructor type.  For example,
1827 the thunk
1828 @
1829         x = case y of (a,b) -> a
1830 @
1831 is a selector thunk.  A selector thunk is laid out like this:
1832 \begin{center}
1833 \begin{tabular}{|l|l|l|l|}\hline
1834 {\em Fixed header}  & {\em Selectee pointer} \\ \hline
1835 \end{tabular}
1836 \end{center}
1837 The @INFO_SM@ word contains the byte offset of the desired word in
1838 the selectee.  Note that this is different from all other thunks.
1839
1840 The garbage collector ``peeks'' at the selectee's
1841 tag (in its info table).  If it is evaluated, then it goes ahead and do
1842 the selection, and then behaves just as if the selector thunk was an
1843 indirection to the selected field.
1844 If it is not
1845 evaluated, it treats the selector thunk like any other thunk of that
1846 shape.  [Implementation notes.  
1847 Copying: only the evacuate routine needs to be special.
1848 Compacting: only the PRStart (marking) routine needs to be special.]
1849 \end{itemize}
1850
1851
1852 The only label associated with a thunk is its info table:
1853 \begin{description}
1854 \item[$f$@_info@] is $f$'s info table.
1855 \end{description}
1856
1857
1858 \subsubsection{Partial applications (PAPs)}\label{sect:PAP}
1859
1860 A partial application (PAP) represents a function applied to too few arguments.
1861 It is only built as a result of updating after an argument-satisfaction
1862 check failure.  A PAP has the following shape:
1863 \begin{center}
1864 \begin{tabular}{|l|l|l|l|}\hline
1865 {\em Fixed header}  & {\em No of arg words} & {\em Function closure} & {\em Arg stack} \\ \hline
1866 \end{tabular}
1867 \end{center}
1868 The ``arg stack'' is a copy of of the chunk of stack above the update
1869 frame; ``no of arg words'' tells how many words it consists of.  The
1870 function closure is (a pointer to) the closure for the function whose
1871 argument-satisfaction check failed.
1872
1873 There is just one standard form of PAP with @INFO_TYPE@ = @PAP@.
1874 There is just one info table too, called @PAP_info@.
1875 Its entry code simply copies the arg stack chunk back on top of the
1876 stack and enters the function closure.  (It has to do a stack overflow test first.)
1877
1878 There are no static PAPs.
1879
1880 \subsubsection{Indirections}
1881 \label{sect:IND}
1882 \label{sect:IND_OLDGEN}
1883
1884 Indirection closures just point to other closures. They are introduced
1885 when a thunk is updated to point to its value. 
1886 The entry code for all indirections simply enters the closure it points to.
1887
1888 There are several forms of indirection:
1889 \begin{description}
1890 \item[@IND@] is the vanilla, dynamically-allocated indirection.
1891 It is removed by the garbage collector. It has the following
1892 shape:
1893 \begin{center}
1894 \begin{tabular}{|l|l|l|}\hline
1895 {\em Fixed header} & {\em Target closure} \\ \hline
1896 \end{tabular}
1897 \end{center}
1898
1899 \item[@IND_OLDGEN@] is the indirection used to update an old-generation
1900 thunk. Its shape is like this:
1901 \begin{center}
1902 \begin{tabular}{|l|l|l|}\hline
1903 {\em Fixed header} & {\em Mutable link field} & {\em Target closure} \\ \hline
1904 \end{tabular}
1905 \end{center}
1906 It contains a {\em mutable link field} that is used to string together
1907 all old-generation indirections that might have a pointer into
1908 the new generation.
1909
1910
1911 \item[@IND_PERMANENT@ and @IND_OLDGEN_PERMANENT@.]
1912 for lexical profiling, it is necessary to maintain cost centre
1913 information in an indirection, so ``permanent indirections'' are
1914 retained forever.  Otherwise they are just like vanilla indirections.
1915 \note{If a permanent indirection points to another permanent
1916 indirection or a @CONST@ closure, it is possible to elide the indirection
1917 since it will have no effect on the profiler.}
1918 \note{Do we still need @IND@ and @IND_OLDGEN@
1919 in the profiling build, or can we just make
1920 do with one pair whose behaviour changes when profiling is built?}
1921
1922 \item[@IND_STATIC@] is used for overwriting CAFs when they have been
1923 evaluated.  Static indirections are not removed by the garbage
1924 collector; and are statically allocated outside the heap (and should
1925 stay there).  Their static object link field is used just as for
1926 @FUN_STATIC@ closures.
1927
1928 \begin{center}
1929 \begin{tabular}{|l|l|l|}
1930 \hline
1931 {\em Fixed header} & {\em Target closure} & {\em Static object link} \\
1932 \hline
1933 \end{tabular}
1934 \end{center}
1935
1936 \end{description}
1937
1938 \subsubsection{Activation Records}
1939
1940 Activation records are parts of the stack described by return address
1941 info tables (closures with @INFO_TYPE@ values of @RET_SMALL@,
1942 @RET_VEC_SMALL@, @RET_BIG@ and @RET_VEC_BIG@). They are described in
1943 section~\ref{sect:activation-records}.
1944
1945
1946 \subsubsection{Black holes, MVars and IVars}
1947 \label{sect:BH}
1948 \label{sect:MVAR}
1949 \label{sect:IVAR}
1950
1951 Black hole closures are used to overwrite closures currently being
1952 evaluated. They inform the garbage collector that there are no live
1953 roots in the closure, thus removing a potential space leak.  
1954
1955 Black holes also become synchronization points in the threaded world.
1956 They contain a pointer to a list of blocked threads to be awakened
1957 when the black hole is updated (or @NULL@ if the list is empty).
1958 \begin{center}
1959 \begin{tabular}{|l|l|l|}
1960 \hline 
1961 {\em Fixed header} & {\em Mutable link} & {\em Blocked thread link} \\
1962 \hline
1963 \end{tabular}
1964 \end{center}
1965 The {\em Blocked thread link} points to the TSO of the first thread
1966 waiting for the value of this thunk.  All subsequent TSOs in the list
1967 are linked together using their @TSO_LINK@ field.
1968
1969 When the blocking queue is non-@NULL@, the black hole must be added to
1970 the mutables list since the TSOs on the list may contain pointers into
1971 the new generation.  There is no need to clutter up the mutables list
1972 with black holes with empty blocking queues.
1973
1974 \ToDo{MVars}
1975
1976
1977 \subsubsection{FetchMes}\label{sect:FETCHME}
1978
1979 In the parallel systems, FetchMes are used to represent pointers into
1980 the global heap.  When evaluated, the value they point to is read from
1981 the global heap.
1982
1983 \ToDo{Describe layout}
1984
1985
1986 \subsection{Unpointed Objects}
1987
1988 A variable of unpointed type is always bound to a {\em value}, never to a {\em thunk}.
1989 For this reason, unpointed objects cannot be entered.
1990
1991 A {\em value} may be:
1992 \begin{itemize}
1993 \item {\em Boxed}, i.e.~represented indirectly by a pointer to a heap object (e.g.~foreign objects, arrays); or
1994 \item {\em Unboxed}, i.e.~represented directly by a bit-pattern in one or more registers (e.g.~@Int#@ and @Float#@).
1995 \end{itemize}
1996 All {\em pointed} values are {\em boxed}.  
1997
1998 \subsubsection{Immutable Objects}
1999 \label{sect:ARR_WORDS1}
2000 \label{sect:ARR_PTRS}
2001
2002 \begin{description}
2003 \item[@ARR_WORDS@] is a variable-sized object consisting solely of
2004 non-pointers.  It is used for arrays of all
2005 sorts of things (bytes, words, floats, doubles... it doesn't matter).
2006 \begin{center}
2007 \begin{tabular}{|c|c|c|c|}
2008 \hline
2009 {\em Fixed Hdr} & {\em No of non-pointers} & {\em Non-pointers\ldots}   \\ \hline
2010 \end{tabular}
2011 \end{center}
2012
2013 \item[@ARR_PTRS@] is an immutable, variable sized array of pointers.
2014 \begin{center}
2015 \begin{tabular}{|c|c|c|c|}
2016 \hline
2017 {\em Fixed Hdr} & {\em Mutable link} & {\em No of pointers} & {\em Pointers\ldots}      \\ \hline
2018 \end{tabular}
2019 \end{center}
2020 The mutable link is present so that we can easily freeze and thaw an
2021 array (by changing the header and adding/removing the array to the
2022 mutables list).
2023
2024 \end{description}
2025
2026 \subsubsection{Mutable Objects}
2027 \label{sect:mutables}
2028 \label{sect:ARR_WORDS2}
2029 \label{sect:MUTVAR}
2030 \label{sect:MUTARR_PTRS}
2031 \label{sect:MUTARR_PTRS_FROZEN}
2032
2033 Some of these objects are {\em mutable}; they represent objects which
2034 are explicitly mutated by Haskell code through the @ST@ monad.
2035 They're not used for thunks which are updated precisely once.
2036 Depending on the garbage collector, mutable closures may contain extra
2037 header information which allows a generational collector to implement
2038 the ``write barrier.''
2039
2040 \begin{description}
2041
2042 \item[@ARR_WORDS@] is also used to represent {\em mutable} arrays of
2043 bytes, words, floats, doubles, etc.  It's possible to use the same
2044 object type because even generational collectors don't need to
2045 distinguish them.
2046
2047 \item[@MUTVAR@] is a mutable variable.
2048 \begin{center}
2049 \begin{tabular}{|c|c|c|}
2050 \hline
2051 {\em Fixed Hdr} & {\em Mutable link} & {\em Pointer} \\ \hline
2052 \end{tabular}
2053 \end{center}
2054
2055 \item[@MUTARR_PTRS@] is a mutable array of pointers.
2056 Such an array may be {\em frozen}, becoming an @SM_MUTARR_PTRS_FROZEN@, with a
2057 different info-table.
2058 \begin{center}
2059 \begin{tabular}{|c|c|c|c|}
2060 \hline
2061 {\em Fixed Hdr} & {\em Mutable link} & {\em No of ptrs} & {\em Pointers\ldots} \\ \hline
2062 \end{tabular}
2063 \end{center}
2064
2065 \item[@MUTARR_PTRS_FROZEN@] is a frozen @MUTARR_PTRS@ closure.
2066 The garbage collector converts @MUTARR_PTRS_FROZEN@ to @ARR_PTRS@ as it removes them from
2067 the mutables list.
2068
2069 \end{description}
2070
2071
2072 \subsubsection{Foreign Objects}\label{sect:FOREIGN}
2073
2074 Here's what a ForeignObj looks like:
2075
2076 \begin{center}
2077 \begin{tabular}{|l|l|l|l|}
2078 \hline 
2079 {\em Fixed header} & {\em Data} & {\em Free Routine} & {\em Foreign object link} \\
2080 \hline
2081 \end{tabular}
2082 \end{center}
2083
2084 The @FreeRoutine@ is a reference to the finalisation routine to call
2085 when the @ForeignObj@ becomes garbage.  If @freeForeignObject@ is
2086 called on a Foreign Object, the @FreeRoutine@ is set to zero and the
2087 garbage collector will not attempt to call @FreeRoutine@ when the 
2088 object becomes garbage.
2089
2090 The Foreign object link is a link to the next foreign object in the
2091 list.  This list is traversed at the end of garbage collection: if an
2092 object is about to be deallocated (e.g.~it was not marked or
2093 evacuated), the free routine is called and the object is deleted from
2094 the list.  
2095
2096
2097 The remaining objects types are all administrative --- none of them may be entered.
2098
2099 \subsection{Thread State Objects (TSOs)}\label{sect:TSO}
2100
2101 In the multi-threaded system, the state of a suspended thread is
2102 packed up into a Thread State Object (TSO) which contains all the
2103 information needed to restart the thread and for the garbage collector
2104 to find all reachable objects.  When a thread is running, it may be
2105 ``unpacked'' into machine registers and various other memory locations
2106 to provide faster access.
2107
2108 Single-threaded systems don't really {\em need\/} TSOs --- but they do
2109 need some way to tell the storage manager about live roots so it is
2110 convenient to use a single TSO to store the mutator state even in
2111 single-threaded systems.
2112
2113 Rather than manage TSOs' alloc/dealloc, etc., in some {\em ad hoc}
2114 way, we instead alloc/dealloc/etc them in the heap; then we can use
2115 all the standard garbage-collection/fetching/flushing/etc machinery on
2116 them.  So that's why TSOs are ``heap objects,'' albeit very special
2117 ones.
2118 \begin{center}
2119 \begin{tabular}{|l|l|}
2120    \hline {\em Fixed header}
2121 \\ \hline @TSO_LINK@
2122 \\ \hline @TSO_WHATNEXT@
2123 \\ \hline @TSO_WHATNEXT_INFO@ 
2124 \\ \hline @TSO_STACK@ 
2125 \\ \hline {\em Exception Handlers}
2126 \\ \hline {\em Ticky Info}
2127 \\ \hline {\em Profiling Info}
2128 \\ \hline {\em Parallel Info}
2129 \\ \hline {\em GranSim Info}
2130 \\ \hline
2131 \end{tabular}
2132 \end{center}
2133 The contents of a TSO are:
2134 \begin{itemize}
2135
2136 \item A pointer (@TSO_LINK@) used to maintain a list of threads with a similar
2137   state (e.g.~all runable, all sleeping, all blocked on the same black
2138   hole, all blocked on the same MVar, etc.)
2139
2140 \item A word (@TSO_WHATNEXT@) which is in suspended threads to record
2141  how to awaken it.  This typically requires a program counter which is stored
2142  in the pointer @TSO_WHATNEXT_INFO@
2143
2144 \item A pointer (@TSO_STACK@) to the top stack block.
2145
2146 \item Optional information for ``Ticky Ticky'' statistics: @TSO_STK_HWM@ is
2147   the maximum number of words allocated to this thread.
2148
2149 \item Optional information for profiling: 
2150   @TSO_CCC@ is the current cost centre.
2151
2152 \item Optional information for parallel execution:
2153 \begin{itemize}
2154
2155 \item The types of threads (@TSO_TYPE@):
2156 \begin{description}
2157 \item[@T_MAIN@]     Must be executed locally.
2158 \item[@T_REQUIRED@] A required thread  -- may be exported.
2159 \item[@T_ADVISORY@] An advisory thread -- may be exported.
2160 \item[@T_FAIL@]     A failure thread   -- may be exported.
2161 \end{description}
2162
2163 \item I've no idea what else
2164
2165 \end{itemize}
2166
2167 \item Optional information for GranSim execution:
2168 \begin{itemize}
2169 \item locked         
2170 \item sparkname  
2171 \item started at         
2172 \item exported   
2173 \item basic blocks       
2174 \item allocs     
2175 \item exectime   
2176 \item fetchtime  
2177 \item fetchcount         
2178 \item blocktime  
2179 \item blockcount         
2180 \item global sparks      
2181 \item local sparks       
2182 \item queue              
2183 \item priority   
2184 \item clock          (gransim light only)
2185 \end{itemize}
2186
2187
2188 Here are the various queues for GrAnSim-type events.
2189 @
2190 Q_RUNNING   
2191 Q_RUNNABLE  
2192 Q_BLOCKED   
2193 Q_FETCHING  
2194 Q_MIGRATING 
2195 @
2196
2197 \end{itemize}
2198
2199 \subsection{Other weird objects}
2200 \label{sect:SPARK}
2201 \label{sect:BLOCKED_FETCH}
2202
2203 \begin{description}
2204 \item[@BlockedFetch@ heap objects (`closures')] (parallel only)
2205
2206 @BlockedFetch@s are inbound fetch messages blocked on local closures.
2207 They arise as entries in a local blocking queue when a fetch has been
2208 received for a local black hole.  When awakened, we look at their
2209 contents to figure out where to send a resume.
2210
2211 A @BlockedFetch@ closure has the form:
2212 \begin{center}
2213 \begin{tabular}{|l|l|l|l|l|l|}\hline
2214 {\em Fixed header} & link & node & gtid & slot & weight \\ \hline
2215 \end{tabular}
2216 \end{center}
2217
2218 \item[Spark Closures] (parallel only)
2219
2220 Spark closures are used to link together all closures in the spark pool.  When
2221 the current processor is idle, it may choose to speculatively evaluate some of
2222 the closures in the pool.  It may also choose to delete sparks from the pool.
2223 \begin{center}
2224 \begin{tabular}{|l|l|l|l|l|l|}\hline
2225 {\em Fixed header} & {\em Spark pool link} & {\em Sparked closure} \\ \hline
2226 \end{tabular}
2227 \end{center}
2228
2229
2230 \end{description}
2231
2232
2233 \subsection{Stack Objects}
2234 \label{sect:STACK_OBJECT}
2235 \label{sect:stacks}
2236
2237 These are ``stack objects,'' which are used in the threaded world as
2238 the stack for each thread is allocated from the heap in smallish
2239 chunks.  (The stack in the sequential world is allocated outside of
2240 the heap.)
2241
2242 Each reduction thread has to have its own stack space.  As there may
2243 be many such threads, and as any given one may need quite a big stack,
2244 a naive give-'em-a-big-stack-and-let-'em-run approach will cost a {\em
2245 lot} of memory.
2246
2247 Our approach is to give a thread a small stack space, and then link
2248 on/off extra ``chunks'' as the need arises.  Again, this is a
2249 storage-management problem, and, yet again, we choose to graft the
2250 whole business onto the existing heap-management machinery.  So stack
2251 objects will live in the heap, be garbage collected, etc., etc..
2252
2253 A stack object is laid out like this:
2254
2255 \begin{center}
2256 \begin{tabular}{|l|}
2257 \hline
2258 {\em Fixed header} 
2259 \\ \hline
2260 {\em Link to next stack object (0 for last)}
2261 \\ \hline
2262 {\em N, the payload size in words}
2263 \\ \hline
2264 {\em @Sp@ (byte offset from head of object)}
2265 \\ \hline
2266 {\em @Su@ (byte offset from head of object)}
2267 \\ \hline
2268 {\em Payload (N words)}
2269 \\ \hline
2270 \end{tabular}
2271 \end{center}
2272
2273 \ToDo{Are stack objects on the mutable list?}
2274
2275 The stack grows downwards, towards decreasing
2276 addresses.  This makes it easier to print out the stack
2277 when debugging, and it means that a return address is
2278 at the lowest address of the chunk of stack it ``knows about''
2279 just like an info pointer on a closure.
2280
2281 The garbage collector needs to be able to find all the
2282 pointers in a stack.  How does it do this?
2283
2284 \begin{itemize}
2285
2286 \item Within the stack there are return addresses, pushed
2287 by @case@ expressions.  Below a return address (i.e. at higher
2288 memory addresses, since the stack grows downwards) is a chunk
2289 of stack that the return address ``knows about'', namely the
2290 activation record of the currently running function.
2291
2292 \item Below each such activation record is a {\em pending-argument
2293 section}, a chunk of
2294 zero or more words that are the arguments to which the result
2295 of the function should be applied.  The return address does not
2296 statically
2297 ``know'' how many pending arguments there are, or their types.
2298 (For example, the function might return a result of type $\alpha$.)
2299
2300 \item Below each pending-argument section is another return address,
2301 and so on.  Actually, there might be an update frame instead, but we
2302 can consider update frames as a special case of a return address with
2303 a well-defined activation record.
2304
2305 \ToDo{Doesn't it {\em have} to be an update frame?  After all, the arg
2306 satisfaction check is @Su - Sp >= ...@.}
2307
2308 \end{itemize}
2309
2310 The game plan is this.  The garbage collector
2311 walks the stack from the top, traversing pending-argument sections and
2312 activation records alternately.  Next we discuss how it finds
2313 the pointers in each of these two stack regions.
2314
2315
2316 \subsubsection{Activation records}\label{sect:activation-records}
2317
2318 An {\em activation record} is a contiguous chunk of stack,
2319 with a return address as its first word, followed by as many
2320 data words as the return address ``knows about''.  The return
2321 address is actually a fully-fledged info pointer.  It points
2322 to an info table, replete with:
2323
2324 \begin{itemize}
2325 \item entry code (i.e. the code to return to).
2326 \item @INFO_TYPE@ is either @RET_SMALL/RET_VEC_SMALL@ or @RET_BIG/RET_VEC_BIG@, depending
2327 on whether the activation record has more than 32 data words (\note{64 for 8-byte-word architectures}) and on whether 
2328 to use a direct or a vectored return.
2329 \item @INFO_SM@ for @RET_SMALL@ is a bitmap telling the layout
2330 of the activation record, one bit per word.  The least-significant bit
2331 describes the first data word of the record (adjacent to the fixed
2332 header) and so on.  A ``@1@'' indicates a non-pointer, a ``@0@''
2333 indicates
2334 a pointer.  We don't need to indicate exactly how many words there
2335 are,
2336 because when we get to all zeros we can treat the rest of the 
2337 activation record as part of the next pending-argument region.
2338
2339 For @RET_BIG@ the @INFO_SM@ field points to a block of bitmap
2340 words, starting with a word that tells how many words are in
2341 the block.
2342
2343 \item @INFO_SRT@ is the Static Reference Table for the return
2344 address (Section~\ref{sect:srt}).
2345 \end{itemize}
2346
2347 The activation record is a fully fledged closure too.
2348 As well as an info pointer, it has all the other attributes of
2349 a fixed header (Section~\ref{sect:fixed-header}) including a saved cost
2350 centre which is reloaded when the return address is entered.
2351
2352 In other words, all the attributes of closures are needed for
2353 activation records, so it's very convenient to make them look alike.
2354
2355
2356 \subsubsection{Pending arguments}
2357
2358 So that the garbage collector can correctly identify pointers
2359 in pending-argument sections we explicitly tag all non-pointers.
2360 Every non-pointer in a pending-argument section is preceded
2361 (at the next lower memory word) by a one-word byte count that
2362 says how many bytes to skip over (excluding the tag word).
2363
2364 The garbage collector traverses a pending argument section from 
2365 the top (i.e. lowest memory address).  It looks at each word in turn:
2366
2367 \begin{itemize}
2368 \item If it is less than or equal to a small constant @MAX_STACK_TAG@
2369 then
2370 it treats it as a tag heralding zero or more words of non-pointers,
2371 so it just skips over them.
2372
2373 \item If it points to the code segment, it must be a return
2374 address, so we have come to the end of the pending-argument section.
2375
2376 \item Otherwise it must be a bona fide heap pointer.
2377 \end{itemize}
2378
2379
2380 \subsection{The Stable Pointer Table}\label{sect:STABLEPTR_TABLE}
2381
2382 A stable pointer is a name for a Haskell object which can be passed to
2383 the external world.  It is ``stable'' in the sense that the name does
2384 not change when the Haskell garbage collector runs---in contrast to
2385 the address of the object which may well change.
2386
2387 A stable pointer is represented by an index into the
2388 @StablePointerTable@.  The Haskell garbage collector treats the
2389 @StablePointerTable@ as a source of roots for GC.
2390
2391 In order to provide efficient access to stable pointers and to be able
2392 to cope with any number of stable pointers (eg $0 \ldots 100000$), the
2393 table of stable pointers is an array stored on the heap and can grow
2394 when it overflows.  (Since we cannot compact the table by moving
2395 stable pointers about, it seems unlikely that a half-empty table can
2396 be reduced in size---this could be fixed if necessary by using a
2397 hash table of some sort.)
2398
2399 In general a stable pointer table closure looks like this:
2400
2401 \begin{center}
2402 \begin{tabular}{|l|l|l|l|l|l|l|l|l|l|l|}
2403 \hline
2404 {\em Fixed header} & {\em No of pointers} & {\em Free} & $SP_0$ & \ldots & $SP_{n-1}$ 
2405 \\\hline
2406 \end{tabular}
2407 \end{center}
2408
2409 The fields are:
2410 \begin{description}
2411
2412 \item[@NPtrs@:] number of (stable) pointers.
2413
2414 \item[@Free@:] the byte offset (from the first byte of the object) of the first free stable pointer.
2415
2416 \item[$SP_i$:] A stable pointer slot.  If this entry is in use, it is
2417 an ``unstable'' pointer to a closure.  If this entry is not in use, it
2418 is a byte offset of the next free stable pointer slot.
2419
2420 \end{description}
2421
2422 When a stable pointer table is evacuated
2423 \begin{enumerate}
2424 \item the free list entries are all set to @NULL@ so that the evacuation
2425   code knows they're not pointers;
2426
2427 \item The stable pointer slots are scanned linearly: non-@NULL@ slots
2428 are evacuated and @NULL@-values are chained together to form a new free list.
2429 \end{enumerate}
2430
2431 There's no need to link the stable pointer table onto the mutable
2432 list because we always treat it as a root.
2433
2434
2435
2436 \section{The Storage Manager}
2437
2438 The generational collector remembers the depth of the last generation
2439 collected and the value of the heap pointer at the end of the last GC.
2440 If the mutator has not moved the heap pointer, that means that the
2441 amount of space recovered is insufficient to satisfy even one request
2442 and it is time to collect an older generation or report a heap overflow.
2443
2444 A deeper collection is also triggered when a minor collection fails to
2445 recover at least @...@ bytes of space.
2446
2447 When can a GC happen?
2448
2449 @
2450 - During updates (ie during returns)
2451 - When a heap check fails
2452 - When a stack check fails (concurrent system only)
2453 - When a context switch happens (concurrent system only)
2454
2455 When do heap checks occur?
2456 - Immediately after entering a thunk
2457 - Immediately after entering a case alternative
2458
2459 When do stack checks occur?
2460 - We calculate the worst-case stack usage of an entire
2461   thunk so there's no need to put a check inside each alternative.
2462 - Immediately after entering a thunk
2463   We can't make a similar worst-case calculation for heap usage
2464   because the heap isn't used in a stacklike manner so any
2465   evaluation inside a case might steal some of the heap we've
2466   checked for.
2467
2468 Concurrency
2469 - Threads can be blocked
2470 - Threads can be put to sleep
2471   - Heap may move while we sleep
2472   - Black holing may happen while we sleep (ie during GC)
2473 @
2474
2475 \subsection{The SM state}
2476
2477 Contains @Hp@, @HpLim@, @StablePtrTable@ plus version-specific info.
2478
2479 \begin{itemize}
2480
2481 \item Static Object list 
2482 \item Foreign Object list
2483 \item Stable Pointer Table
2484
2485 \end{itemize}
2486
2487 In addition, the generational collector requires:
2488
2489 \begin{itemize}
2490
2491 \item Old Generation Indirection list
2492 \item Mutables list --- list of mutable objects in the old generation.
2493 \item @OldLim@ --- the boundary between the generations
2494 \item Old Foreign Object list --- foreign objects in the old generation
2495
2496 \end{itemize}
2497
2498 It is passed a table of {\em roots\/} containing
2499
2500 \begin{itemize}
2501
2502 \item All runnable TSOs
2503
2504 \end{itemize}
2505
2506
2507 In the parallel system, there must be some extra magic associated with
2508 global GC.
2509
2510 \subsection{The SM interface}
2511
2512 @initSM@ finalizes any runtime parameters of the storage manager.
2513
2514 @exitSM@ does any cleaning up required by the storage manager before
2515 the program is executed. Its main purpose is to print any summary
2516 statistics.
2517
2518 @initHeap@ allocates the heap. It initialises the @hp@ and @hplim@
2519 fields of @sm@ to represent an empty heap for the compiled-in garbage
2520 collector.  It also initialises @CAFlist@ to be the empty list. If we
2521 are using Appel's collector it also initialises the @OldLim@ field.
2522 It also initialises the stable pointer table and the @ForeignObjList@
2523 (and @OldForeignObjList@) fields.
2524
2525 @collectHeap@ invokes the garbage collector.  @collectHeap@ requires
2526 all the fields of @sm@ to be initialised appropriately (from the
2527 STG-machine registers).  The following are identified as heap roots:
2528 \begin{itemize}
2529 \item The updated CAFs recorded in @CAFlist@.
2530 \item Any pointers found on the stack.
2531 \item All runnable and sleeping TSOs.
2532 \item The stable pointer table.
2533 \end{itemize}
2534
2535 There are two possible results from a garbage collection:
2536 \begin{description} 
2537 \item[@GC_FAIL@] 
2538 The garbage collector is unable to free up any more space.
2539
2540 \item[@GC_SUCCESS@]
2541 The garbage collector managed to free up more space.
2542
2543 \begin{itemize} 
2544 \item @hp@ and @hplim@ will indicate the new space available for
2545 allocation.
2546
2547 \item The elements of @CAFlist@ and the stable pointers will be
2548 updated to point to the new locations of the closures they reference.
2549
2550 \item Any members of @ForeignObjList@ which became garbage should have
2551 been reported (by calling their finalising routines; and the
2552 @(Old)ForeignObjList@ updated to contain only those Foreign objects
2553 which are still live.  
2554
2555 \end{itemize}
2556
2557 \end{description}
2558
2559
2560 %************************************************************************
2561 %*                                                                      *
2562 \subsection{``What really happens in a garbage collection?''}
2563 %*                                                                      *
2564 %************************************************************************
2565
2566 This is a brief tutorial on ``what really happens'' going to/from the
2567 storage manager in a garbage collection.
2568
2569 \begin{description}
2570 %------------------------------------------------------------------------
2571 \item[The heap check:]
2572
2573 [OLD-ISH: WDP]
2574
2575 If you gaze into the C output of GHC, you see many macros calls like:
2576 \begin{verbatim}
2577 HEAP_CHK_2PtrsLive((_FHS+2));
2578 \end{verbatim}
2579
2580 This expands into the C (roughly speaking...):
2581 @
2582 Hp = Hp + (_FHS+2);     /* optimistically move heap pointer forward */
2583
2584 GC_WHILE_OR_IF (HEAP_OVERFLOW_OP(Hp, HpLim) OR_INTERVAL_EXPIRED) {
2585         STGCALL2_GC(PerformGC, <liveness-bits>, (_FHS+2));
2586 }
2587 @
2588
2589 In the parallel world, where we will need to re-try the heap check,
2590 @GC_WHILE_OR_IF@ will be a ``while''; in the sequential world, it will
2591 be an ``if''.
2592
2593 The ``heap lookahead'' checks, which are similar and used for
2594 multi-precision @Integer@ ops, have some further complications.  See
2595 the commentary there (@StgMacros.lh@).
2596
2597 %------------------------------------------------------------------------
2598 \item[Into @callWrapper_GC@...:]
2599
2600 When we failed the heap check (above), we were inside the
2601 GCC-registerised ``threaded world.''  @callWrapper_GC@ is all about
2602 getting in and out of the threaded world.  On SPARCs, with register
2603 windows, the name of the game is not shifting windows until we have
2604 what we want out of the old one.  In tricky cases like this, it's best
2605 written in assembly language.
2606
2607 Performing a GC (potentially) means giving up the thread of control.
2608 So we must fill in the thread-state-object (TSO) [and its associated
2609 stk object] with enough information for later resumption:
2610 \begin{enumerate}
2611 \item
2612 Save the return address in the TSO's PC field.
2613 \item
2614 Save the machine registers used in the STG threaded world in their
2615 corresponding TSO fields.  We also save the pointer-liveness
2616 information in the TSO.
2617 \item
2618 The registers that are not thread-specific, notably @Hp@ and
2619 @HpLim@, are saved in the @StorageMgrInfo@ structure.
2620 \item
2621 Call the routine it was asked to call; in this example, call
2622 @PerformGC@ with arguments @<liveness>@ and @_FHS+2@ (some constant)...
2623
2624 \end{enumerate}
2625
2626 %------------------------------------------------------------------------
2627 \item[Into the heap overflow wrapper, @PerformGC@ [parallel]:]
2628
2629 Most information has already been saved in the TSO.
2630
2631 \begin{enumerate}
2632 \item
2633 The first argument (@<liveness>@, in our example) say what registers
2634 are live, i.e., are ``roots'' the storage manager needs to know.
2635 \begin{verbatim}
2636 StorageMgrInfo.rootno   = 2;
2637 StorageMgrInfo.roots[0] = (P_) Ret1_SAVE;
2638 StorageMgrInfo.roots[1] = (P_) Ret2_SAVE;
2639 \end{verbatim}
2640
2641 \item
2642 We move the heap-pointer back [we had optimistically
2643 advanced it, in the initial heap check]
2644
2645 \item 
2646 We load up the @smInfo@ data from the STG registers' @*_SAVE@ locations.
2647
2648 \item
2649 We mark on the scheduler's big ``blackboard'' that a GC is
2650 required.
2651
2652 \item
2653 We reschedule, i.e., this thread gives up control.  (The scheduler
2654 will presumably initiate a garbage-collection, but it may have to do
2655 any number of other things---flushing, for example---before ``normal
2656 execution'' resumes; and it most certainly may not be this thread that
2657 resumes at that point!)
2658 \end{enumerate}
2659
2660 IT IS AT THIS POINT THAT THE WORLD IS COMPLETELY TIDY.
2661
2662 %------------------------------------------------------------------------
2663 \item[Out of @callWrapper_GC@ [parallel]:]
2664
2665 When this thread is finally resumed after GC (and who knows what
2666 else), it will restart by the normal enter-TSO/enter-stack-object
2667 sequence, which has the effect of re-loading the registers, etc.,
2668 (i.e., restoring the state).
2669
2670 Because the address we saved in the TSO's PC field was that at the end
2671 of the heap check, and because the check is a while-loop in the
2672 parallel system, we will now loop back around, and make sure there is
2673 enough space before continuing.
2674 \end{description}
2675
2676
2677
2678 \subsection{Static Reference Tables (SRTs)}
2679 \label{sect:srt}
2680 \label{sect:CAF}
2681 \label{sect:static-objects}
2682
2683 In the above, we assumed that objects always contained pointers to all
2684 their free variables.  In fact, this isn't quite true: GHC omits
2685 pointers to top-level objects and allocates their closures in static
2686 memory.  This optimisation reduces the number of free variables in
2687 heap objects - reducing memory usage and the effort needed to put them
2688 into heap objects.  However, this optimisation comes at a cost: we
2689 need to complicate the garbage collector with machinery for tracing
2690 these static references.
2691
2692 Early versions of GHC used a very simple algorithm: it treated all
2693 static objects as roots.  This is safe in the sense that no object is
2694 ever deallocated if there's a chance that it might be required later
2695 but can lead to some terrible space leaks.  For example, this program
2696 ought to be able to run in constant space but, because @xs@ is never
2697 deallocated, it runs in linear space.
2698
2699 @
2700 main = print xs
2701 xs = [1..]
2702 @
2703
2704 The correct behaviour is for the garbage collector to keep a static
2705 object alive iff it might be required later in execution.  That is, if
2706 it is reachable from any live heap objects {\em or\/} from any return
2707 addresses found on the stack or from the current program counter.
2708 Since it is obviously infeasible for the garbage collector to scan
2709 machine code looking for static references, the code generator must
2710 generate a table of all static references in any piece of code (and we
2711 must place a pointer to this table next to any piece of code we
2712 generate).
2713
2714 Here's what the SRT has to contain:
2715
2716 @
2717 ...
2718 @
2719
2720 Here's how we represent it:
2721
2722 @
2723 ...
2724 must be able to handle 0 references well
2725 @
2726
2727 @
2728 Other trickery:
2729 o The CAF list
2730 o The scavenge list
2731 o Generational GC trickery
2732 @
2733
2734 \subsection{Space leaks and black holes}
2735 \label{sect:black-hole}
2736
2737 \iffalse
2738
2739 \ToDo{Insert text stolen from update paper}
2740
2741 \else
2742
2743 A program exhibits a {\em space leak} if it retains storage that is
2744 sure not to be used again.  Space leaks are becoming increasingly
2745 common in imperative programs that @malloc@ storage and fail
2746 subsequently to @free@ it.  They are, however, also common in
2747 garbage-collected systems, especially where lazy evaluation is
2748 used.[.wadler leak, runciman heap profiling jfp.]
2749
2750 Quite a bit of experience has now accumulated suggesting that
2751 implementors must be very conscientious about avoiding gratuitous
2752 space leaks --- that is, ones which are an accidental artefact of some
2753 implementation technique.[.appel book.]  The update mechanism is
2754 a case in point, as <.jones jfp leak.> points out.  Consider a thunk for
2755 the expression
2756 @
2757   let xs = [1..1000] in last xs
2758 @
2759 where @last@ is a function that returns the last element of its
2760 argument list.  When the thunk is entered it will call @last@, which
2761 will consume @xs@ until it finds the last element.  Since the list
2762 @[1..1000]@ is produced lazily one might reasonably expect the
2763 expression to evaluate in constant space.  But {\em until the moment
2764 of update, the thunk itself still retains a pointer to the beginning
2765 of the list @xs@}.  So, until the update takes place the whole list
2766 will be retained!
2767
2768 Of course, this is completely gratuitous.  The pointer to @xs@ in the
2769 thunk will never be used again.  In <.peyton stock hardware.> the solution to
2770 this problem that we advocated was to overwrite a thunk's info with a
2771 fixed ``black hole'' info pointer, {\em at the moment of entry}.  The
2772 storage management information attached to a black-hole info pointer
2773 tells the garbage collector that the closure contains no pointers,
2774 thereby plugging the space leak.
2775
2776 \subsubsection{Lazy black-holing}
2777
2778 Black-holing is a well-known idea.  The trouble is that it is
2779 gallingly expensive.  To avoid the occasional space leak, for every
2780 single thunk entry we have to load a full-word literal constant into a
2781 register (often two instructions) and then store that register into a
2782 memory location.  
2783
2784 Fortunately, this cost can easily be avoided.  The
2785 idea is simple: {\em instead of black-holing every thunk on entry,
2786 wait until the garbage collector is called, and then black-hole all
2787 (and only) the thunks whose evaluation is in progress at that moment}.
2788 There is no benefit in black-holing a thunk that is updated before
2789 garbage collection strikes!  In effect, the idea is to perform the
2790 black-holing operation lazily, only when it is needed.  This
2791 dramatically cuts down the number of black-holing operations, as our
2792 results show {\em forward ref}.
2793
2794 How can we find all the thunks whose evaluation is in progress?  They
2795 are precisely the ones for which update frames are on the stack.  So
2796 all we need do is find all the update frames (via the @Su@ chain) and
2797 black-hole their thunks right at the start of garbage collection.
2798 Notice that it is not enough to refrain from treating update frames as
2799 roots: firstly because the thunks to which they point may need to be
2800 moved in a copying collector, but more importantly because the thunk
2801 might be accessible via some other route.
2802
2803 \subsubsection{Detecting loops}
2804
2805 Black-holing has a second minor advantage: evaluation of a thunk whose
2806 value depends on itself will cause a black hole closure to be entered,
2807 which can cause a suitable error message to be displayed. For example,
2808 consider the definition
2809 @
2810   x = 1+x
2811 @
2812 The code to evaluate @x@'s right hand side will evaluate @x@.  In the
2813 absence of black-holing, the result will be a stack overflow, as the
2814 evaluator repeatedly pushes a return address and enters @x@.  If
2815 thunks are black-holed on entry, then this infinite loop can be caught
2816 almost instantly.
2817
2818 With our new method of lazy black-holing, a self-referential program
2819 might cause either stack overflow or a black-hole error message,
2820 depending on exactly when garbage collection strikes.  It is quite
2821 easy to conceal these differences, however.  If stack overflow occurs,
2822 all we need do is examine the update frames on the stack to see if
2823 more than one refers to the same thunk.  If so, there is a loop that
2824 would have been detected by eager black-holing.
2825
2826 \subsubsection{Lazy locking}
2827 \label{sect:lock}
2828
2829 In a parallel implementation, it is necessary somehow to ``lock'' a
2830 thunk that is under evaluation, so that other parallel evaluators
2831 cannot simultaneously evaluate it and thereby duplicate work.
2832 Instead, an evaluator that enters a locked thunk should be blocked,
2833 and made runnable again when the thunk is updated.
2834
2835 This locking is readily arranged in the same way as black-holing, by
2836 overwriting the thunk's info pointer with a special ``locked'' info
2837 pointer, at the moment of entry.  If another evaluator enters the
2838 thunk before it has been updated, it will land in the entry code for
2839 the ``locked'' info pointer, which blocks the evaluator and queues it
2840 on the locked thunk.
2841
2842 The details are given by <.portable parallel trinder.>.  However, the close similarity
2843 between locking and black holing suggests the following question: can
2844 locking be done lazily too?  The answer is that it can, except that
2845 locking can be postponed only until the next {\em context switch},
2846 rather than the next {\em garbage collection}.  We are assuming here
2847 that the parallel implementation does not use shared memory to allow
2848 two processors to access the same closure.  If such access is
2849 permitted then every thunk entry requires a hardware lock, and becomes
2850 much too expensive.
2851
2852 Is lazy locking worth while, given that it requires extra work every
2853 context switch?  We believe it is, because contexts switches are
2854 relatively infrequent, and thousands of thunk-entries typically take
2855 place between each.
2856
2857 {\em Measurements elsewhere.  Omit this section? If so, fix cross refs to here.}
2858
2859 \fi
2860
2861
2862 \subsection{Squeezing identical updates}
2863
2864 \iffalse
2865
2866 \ToDo{Insert text stolen from update paper}
2867
2868 \else
2869
2870 Consider the following Haskell definition of the standard
2871 function @partition@ that divides a list into two, those elements
2872 that satisfy a predicate @p@ and those that do not:
2873 @
2874   partition :: (a->Bool) -> [a] -> ([a],[a])
2875   partition p [] = ([],[])
2876   partition p (x:xs) = if p x then (x:ys, zs)
2877                               else (ys, x:zs)
2878                      where
2879                        (ys,zs) = partition p xs
2880 @
2881 By the time this definition has been desugared, it looks like this:
2882 @
2883   partition p xs
2884     = case xs of
2885         [] -> ([],[])
2886         (x:xs) -> let
2887                     t = partition p xs
2888                     ys = fst t
2889                     zs = snd t
2890                   in
2891                   if p x then (x:ys,zs)
2892                          else (ys,x:zs)
2893 @
2894 Lazy evaluation demands that the recursive call is bound to an
2895 intermediate variable, @t@, from which @ys@ and @zs@ are lazily
2896 selected. (The functions @fst@ and @snd@ select the first and second
2897 elements of a pair, respectively.)
2898
2899 Now, suppose that @partition@ is applied to a list @[x1,x2]@,
2900 all of whose
2901 elements satisfy @p@.  We can get a good idea of what will happen
2902 at runtime by unrolling the recursion a few times in our heads.
2903 Unrolling once, and remembering that @(p x1)@ is @True@, we get this:
2904 @
2905   partition p [x1,x2]
2906 =
2907   let t1 = partition [x2]
2908       ys1 = fst t1
2909       zs1 = snd t1
2910   in (x1:ys1, zs1)
2911 @
2912 Unrolling the rest of the way gives this:
2913 @
2914   partition p [x1,x2]
2915 =
2916   let t2  = ([],[])
2917       ys2 = fst t2
2918       zs2 = snd t2
2919       t1  = (x2:ys2,zs2)
2920       ys1 = fst t1
2921       zs1 = snd t1
2922    in (x1:ys1,zs1)
2923 @
2924 Now consider what happens if @zs1@ is evaluated.  It is bound to a
2925 thunk, which will push an update frame before evaluating the
2926 expression @snd t1@.  This expression in turn forces evaluation of
2927 @zs2@, which pushes an update frame before evaluating @snd t2@.
2928 Indeed the stack of update frames will grow as deep as the list is
2929 long when @zs1@ is evaluated.  This is rather galling, since all the
2930 thunks @zs1@, @zs2@, and so on, have the same value.
2931
2932 \ToDo{Describe the state-transformer case in which we get a space leak from
2933 pending update frames.}
2934
2935 The solution is simple.  The garbage collector, which is going to traverse the
2936 update stack in any case, can easily identify two update frames that are directly
2937 on top of each other.  The second of these will update its target with the same
2938 value as the first.  Therefore, the garbage collector can perform the update 
2939 right away, by overwriting one update target with an indirection to the second,
2940 and eliminate the corresponding update frame.  In this way ever-growing stacks of
2941 update frames are reduced to a single representative at garbage collection time.
2942 If this is done at the start of garbage collection then, if it turns out that
2943 some of these update targets are garbage they will be collected right away.
2944
2945 \fi
2946
2947 \subsection{Space leaks and selectors}\label{sect:space-leaks-and-selectors}
2948
2949 \iffalse
2950
2951 \ToDo{Insert text stolen from update paper}
2952
2953 \else
2954
2955 In 1987, Wadler identified an important source of space leaks in
2956 lazy functional programs.  Consider the Haskell function definition:
2957 @
2958   f p = (g1 a, g2 b) where (a,b) = p
2959 @
2960 The pattern-matching in the @where@ clause is known as
2961 {\em lazy pattern-matching}, because it is performed only if @a@
2962 or @b@ is actually evaluated.  The desugarer translates lazy pattern matching
2963 to the use of selectors, @fst@ and @snd@ in this case:
2964 @
2965   f p = let a = fst p
2966             b = snd p
2967         in
2968         (b, a)
2969 @
2970 Now suppose that the second component of the pair @(f p)@, namely @a@,
2971 is evaluated and discarded, but the first is not although it remains
2972 reachable.  The garbage collector will find that the thunk for @b@ refers
2973 to @p@ and hence to @a@.  Thus, although @a@ cannot ever be used again, its
2974 space is retained.  It turns out that this space leak can have a very bad effect
2975 indeed on a program's space behaviour (Section~\ref{sect:selector-results}).
2976
2977 Wadler's paper also proposed a solution: if the garbage collector
2978 encounters a thunk of the form @snd p@, where @p@ is evaluated, then
2979 the garbage collector should perform the selection and overwrite the
2980 thunk with a pointer to the second component of the pair.  In effect, the
2981 garbage collector thereby performs a bounded amount of as-yet-undemanded evaluation
2982 in the hope of improving space behaviour.
2983 We implement this idea directly, by making the garbage collector
2984 eagerly execute all selector thunks\footnote{A word of caution: it is rather easy 
2985 to make a mistake in the implementation, especially if the garbage collector
2986 uses pointer reversal to traverse the reachable graph.},
2987 with results 
2988 reported in Section~\ref{sect:THUNK_SEL}.
2989
2990 One could easily imagine generalisations of this idea, with the garbage 
2991 collector performing bounded amounts of space-saving work.  One example is
2992 this:
2993 @
2994   f x []     = (x,x)
2995   f x (y:ys) = f (x+1) ys
2996 @
2997 Most lazy evaluators will build up a chain of thunks for the accumulating
2998 parameter, @x@, each of which increments @x@.  It is not safe to evaluate
2999 any of these thunks eagerly, since @f@ is not strict in @x@, and we know nothing
3000 about the value of @x@ passed in the initial call to @f@.
3001 On the other hand, if the garbage collector found a thunk @(x+1)@ where
3002 @x@ happened to be evaluated, then it could ``execute'' it eagerly.
3003 If done carefully, the entire chain could be eliminated in a single
3004 garbage collection.   We have not (yet) implemented this idea.
3005 A very similar idea, dubbed ``stingy evaluation'', is described 
3006 by <.stingy.>.
3007
3008 \ToDo{Simple generalisation: handle all the ``standard closures'' this way.}
3009
3010 <.sparud lazy pattern matching.> describes another solution to the
3011 lazy-pattern-matching
3012 problem.  His solution involves adding code to the two thunks for
3013 @a@ and @b@ so that if either is evaluated it arranges to update the
3014 other as well as itself.  The garbage-collector solution is a little
3015 more general, since it applies whether or not the selectors were
3016 generated by lazy pattern matching, and in our setting it was easier
3017 to implement than Sparud's.
3018
3019 \fi
3020
3021
3022 \subsection{Internal workings of the Compacting Collector}
3023
3024 \subsection{Internal workings of the Copying Collector}
3025
3026 \subsection{Internal workings of the Generational Collector}
3027
3028
3029 \section{Dynamic Linking}
3030
3031 \section{Profiling}
3032
3033 Registering costs centres looks awkward - can we tidy it up?
3034
3035 \section{Parallelism}
3036
3037 Something about global GC, inter-process messages and fetchmes.
3038
3039 \section{Debugging}
3040
3041 \section{Ticky Ticky profiling}
3042
3043 Measure what proportion of ...:
3044 \begin{itemize}
3045 \item
3046 ... Enters are to data values, function values, thunks.
3047 \item
3048 ... allocations are for data values, functions values, thunks.
3049 \item
3050 ... updates are for data values, function values.
3051 \item
3052 ... updates ``fit''
3053 \item
3054 ... return-in-heap (dynamic)
3055 \item
3056 ... vectored return (dynamic)
3057 \item
3058 ... updates are wasted (never re-entered).
3059 \item
3060 ... constructor returns get away without hitting an update.
3061 \end{itemize}
3062
3063 %************************************************************************
3064 %*                                                                      *
3065 \subsubsection[ticky-stk-heap-use]{Stack and heap usage}
3066 %*                                                                      *
3067 %************************************************************************
3068
3069 Things we are interested in here:
3070 \begin{itemize}
3071 \item
3072 How many times we do a heap check and move @Hp@; comparing this with
3073 the allocations gives an indication of how many things we get per trip
3074 to the well:
3075
3076 If we do a ``heap lookahead,'' we haven't really allocated any
3077 heap, so we need to undo the effects of an @ALLOC_HEAP@:
3078
3079 \item
3080 The stack high-water mark.
3081
3082 \item
3083 Re-use of stack slots, and stubbing of stack slots:
3084
3085 \end{itemize}
3086
3087 %************************************************************************
3088 %*                                                                      *
3089 \subsubsection[ticky-allocs]{Allocations}
3090 %*                                                                      *
3091 %************************************************************************
3092
3093 We count things every time we allocate something in the dynamic heap.
3094 For each, we count the number of words of (1)~``admin'' (header),
3095 (2)~good stuff (useful pointers and data), and (3)~``slop'' (extra
3096 space, in hopes it will allow an in-place update).
3097
3098 The first five macros are inserted when the compiler generates code
3099 to allocate something; the categories correspond to the @ClosureClass@
3100 datatype (manifest functions, thunks, constructors, big tuples, and
3101 partial applications).
3102
3103 We may also allocate space when we do an update, and there isn't
3104 enough space.  These macros suffice (for: updating with a partial
3105 application and a constructor):
3106
3107 In the threaded world, we allocate space for the spark pool, stack objects,
3108 and thread state objects.
3109
3110 The histogrammy bit is fairly straightforward; the @-2@ is: one for
3111 0-origin C arrays; the other one because we do {\em no} one-word
3112 allocations, so we would never inc that histogram slot; so we shift
3113 everything over by one.
3114
3115 Some hard-to-account-for words are allocated by/for primitives,
3116 includes Integer support.  @ALLOC_PRIM2@ tells us about these.  We
3117 count everything as ``goods'', which is not strictly correct.
3118 (@ALLOC_PRIM@ is the same sort of stuff, but we know the
3119 admin/goods/slop breakdown.)
3120
3121 %************************************************************************
3122 %*                                                                      *
3123 \subsubsection[ticky-enters]{Enters}
3124 %*                                                                      *
3125 %************************************************************************
3126
3127 We do more magical things with @ENT_FUN_DIRECT@.  Besides simply knowing
3128 how many ``fast-entry-point'' enters there were, we'd like {\em simple}
3129 information about where those enters were, and the properties thereof.
3130 @
3131 struct ent_counter {
3132     unsigned    registeredp:16, /* 0 == no, 1 == yes */
3133                 arity:16,       /* arity (static info) */
3134                 Astk_args:16,   /* # of args off A stack */
3135                 Bstk_args:16;   /* # of args off B stack */
3136                                 /* (rest of args are in registers) */
3137     StgChar     *f_str;         /* name of the thing */
3138     StgChar     *f_arg_kinds;   /* info about the args types */
3139     StgChar     *wrap_str;      /* name of its wrapper (if any) */
3140     StgChar     *wrap_arg_kinds;/* info about the orig wrapper's arg types */
3141     I_          ctr;            /* the actual counter */
3142     struct ent_counter *link;   /* link to chain them all together */
3143 };
3144 @
3145
3146 %************************************************************************
3147 %*                                                                      *
3148 \subsubsection[ticky-returns]{Returns}
3149 %*                                                                      *
3150 %************************************************************************
3151
3152 Whenever a ``return'' occurs, it is returning the constituent parts of
3153 a data constructor.  The parts can be returned either in registers, or
3154 by allocating some heap to put it in (the @ALLOC_*@ macros account for
3155 the allocation).  The constructor can either be an existing one
3156 (@*OLD*@) or we could have {\em just} figured out this stuff
3157 (@*NEW*@).
3158
3159 Here's some special magic that Simon wants [edited to match names
3160 actually used]:
3161
3162 @
3163 From: Simon L Peyton Jones <simonpj>
3164 To: partain, simonpj
3165 Subject: counting updates
3166 Date: Wed, 25 Mar 92 08:39:48 +0000
3167
3168 I'd like to count how many times we update in place when actually Node
3169 points to the thing.  Here's how:
3170
3171 @RET_OLD_IN_REGS@ sets the variable @ReturnInRegsNodeValid@ to @True@;
3172 @RET_NEW_IN_REGS@ sets it to @False@.
3173
3174 @RET_SEMI_???@ sets it to??? ToDo [WDP]
3175
3176 @UPD_CON_IN_PLACE@ tests the variable, and increments @UPD_IN_PLACE_COPY_ctr@
3177 if it is true.
3178
3179 Then we need to report it along with the update-in-place info.
3180 @
3181
3182
3183 Of all the returns (sum of four categories above), how many were
3184 vectored?  (The rest were obviously unvectored).
3185
3186 %************************************************************************
3187 %*                                                                      *
3188 \subsubsection[ticky-update-frames]{Update frames}
3189 %*                                                                      *
3190 %************************************************************************
3191
3192 These macros count up the following update information.
3193
3194 \begin{tabular}{|l|l|} \hline
3195 Macro                   &       Counts                                  \\ \hline
3196                         &                                               \\
3197 @UPDF_STD_PUSHED@       &       Update frame pushed                     \\
3198 @UPDF_CON_PUSHED@       &       Constructor update frame pushed         \\
3199 @UPDF_HOLE_PUSHED@      &       An update frame to update a black hole  \\
3200 @UPDF_OMITTED@          &       A thunk decided not to push an update frame \\
3201                         &       (all subsets of @ENT_THK@)              \\
3202 @UPDF_RCC_PUSHED@       &       Cost Centre restore frame pushed        \\
3203 @UPDF_RCC_OMITTED@      &       Cost Centres not required -- not pushed \\\hline
3204 \end{tabular}
3205
3206 %************************************************************************
3207 %*                                                                      *
3208 \subsubsection[ticky-updates]{Updates}
3209 %*                                                                      *
3210 %************************************************************************
3211
3212 These macros record information when we do an update.  We always
3213 update either with a data constructor (CON) or a partial application
3214 (PAP).
3215
3216 \begin{tabular}{|l|l|}\hline
3217 Macro                   &       Where                                           \\ \hline
3218                         &                                                       \\
3219 @UPD_EXISTING@          &       Updating with an indirection to something       \\
3220                         &       already in the heap                             \\
3221 @UPD_SQUEEZED@          &       Same as @UPD_EXISTING@ but because              \\
3222                         &       of stack-squeezing                              \\
3223 @UPD_CON_W_NODE@        &       Updating with a CON: by indirecting to Node     \\
3224 @UPD_CON_IN_PLACE@      &       Ditto, but in place                             \\
3225 @UPD_CON_IN_NEW@        &       Ditto, but allocating the object                \\
3226 @UPD_PAP_IN_PLACE@      &       Same, but updating w/ a PAP                     \\
3227 @UPD_PAP_IN_NEW@        &                                                       \\\hline
3228 \end{tabular}
3229
3230 %************************************************************************
3231 %*                                                                      *
3232 \subsubsection[ticky-selectors]{Doing selectors at GC time}
3233 %*                                                                      *
3234 %************************************************************************
3235
3236 @GC_SEL_ABANDONED@: we could've done the selection, but we gave up
3237 (e.g., to avoid overflowing the C stack); @GC_SEL_MINOR@: did a
3238 selection in a minor GC; @GC_SEL_MAJOR@: ditto, but major GC.
3239
3240
3241
3242 \section{History}
3243
3244 We're nuking the following:
3245
3246 \begin{itemize}
3247 \item
3248   Two stacks
3249
3250 \item
3251   Return in registers.
3252   This lets us remove update code pointers from info tables,
3253   removes the need for phantom info tables, simplifies 
3254   semi-tagging, etc.
3255
3256 \item
3257   Threaded GC.
3258   Careful analysis suggests that it doesn't buy us very much
3259   and it is hard to work with.
3260
3261   Eliminating threaded GCs eliminates the desire to share SMReps
3262   so they are (once more) part of the Info table.
3263
3264 \item
3265   RetReg.
3266   Doesn't buy us anything on a register-poor architecture and
3267   isn't so important if we have semi-tagging.
3268
3269 @
3270     - Probably bad on register poor architecture 
3271     - Can avoid need to write return address to stack on reg rich arch.
3272       - when a function does a small amount of work, doesn't 
3273         enter any other thunks and then returns.
3274         eg entering a known constructor (but semitagging will catch this)
3275     - Adds complications
3276 @
3277
3278 \item
3279   Update in place
3280
3281   This lets us drop CONST closures and CHARLIKE closures (assuming we
3282   don't support Unicode).  The only point of these closures was to 
3283   avoid updating with an indirection.
3284
3285   We also drop @MIN_UPD_SIZE@ --- all we need is space to insert an
3286   indirection or a black hole.
3287
3288 \item
3289   STATIC SMReps are now called CONST
3290
3291 \item
3292   @SM_MUTVAR@ is new
3293
3294 \item The profiling ``kind'' field is now encoded in the @INFO_TYPE@ field.
3295 This identifies the general sort of the closure for profiling purposes.
3296
3297 \item Various papers describe deleting update frames for unreachable objects.
3298   This has never been implemented and we don't plan to anytime soon.
3299
3300 \end{itemize}
3301
3302 \section{Old tricks}
3303
3304 @CAF@ indirections:
3305
3306 These are statically defined closures which have been updated with a
3307 heap-allocated result.  Initially these are exactly the same as a
3308 @STATIC@ closure but with special entry code. On entering the closure
3309 the entry code must:
3310
3311 \begin{itemize}
3312 \item Allocate a black hole in the heap which will be updated with
3313       the result.
3314 \item Overwrite the static closure with a special @CAF@ indirection.
3315
3316 \item Link the static indirection onto the list of updated @CAF@s.
3317 \end{itemize}
3318
3319 The indirection and the link field require the initial @STATIC@
3320 closure to be of at least size @MIN_UPD_SIZE@ (excluding the fixed
3321 header).
3322
3323 @CAF@s are treated as special garbage collection roots.  These roots
3324 are explicitly collected by the garbage collector, since they may
3325 appear in code even if they are not linked with the main heap.  They
3326 consequently represent potentially enormous space-leaks.  A @CAF@
3327 closure retains a fixed location in statically allocated data space.
3328 When updated, the contents of the @CAF@ indirection are changed to
3329 reflect the new closure. @CAF@ indirections require special garbage
3330 collection code.
3331
3332 \section{Old stuff about SRTs}
3333
3334 Garbage collection of @CAF@s is tricky.  We have to cope with explicit
3335 collection from the @CAFlist@ as well as potential references from the
3336 stack and heap which will cause the @CAF@ evacuation code to be
3337 called.  They are treated like indirections which are shorted out.
3338 However they must also be updated to point to the new location of the
3339 new closure as the @CAF@ may still be used by references which
3340 reside in the code.
3341
3342 {\bf Copying Collection}
3343
3344 A first scheme might use evacuation code which evacuates the reference
3345 and updates the indirection. This is no good as subsequent evacuations
3346 will result in an already evacuated closure being evacuated. This will
3347 leave a forward reference in to-space!
3348
3349 An alternative scheme evacuates the @CAFlist@ first. The closures
3350 referenced are evacuated and the @CAF@ indirection updated to point to
3351 the evacuated closure. The @CAF@ evacuation code simply returns the
3352 updated indirection pointer --- the pointer to the evacuated closure.
3353 Unfortunately the closure the @CAF@ references may be a static
3354 closure, in fact, it may be another @CAF@. This will cause the second
3355 @CAF@'s evacuation code to be called before the @CAF@ has been
3356 evacuated, returning an unevacuated pointer.
3357
3358 Another scheme leaves updating the @CAF@ indirections to the end of
3359 the garbage collection.  All the references are evacuated and
3360 scavenged as usual (including the @CAFlist@). Once collection is
3361 complete the @CAFlist@ is traversed updating the @CAF@ references with
3362 the result of evacuating the referenced closure again. This will
3363 immediately return as it must be a forward reference, a static
3364 closure, or a @CAF@ which will indirect by evacuating its reference.
3365
3366 The crux of the problem is that the @CAF@ evacuation code needs to
3367 know if its reference has already been evacuated and updated. If not,
3368 then the reference can be evacuated, updated and returned safely
3369 (possibly evacuating another @CAF@). If it has, then the updated
3370 reference can be returned. This can be done using two @CAF@
3371 info-tables. At the start of a collection the @CAFlist@ is traversed
3372 and set to an internal {\em evacuate and update} info-table. During
3373 collection, evacution of such a @CAF@ also results in the info-table
3374 being reset back to the standard @CAF@ info-table. Thus subsequent
3375 evacuations will simply return the updated reference. On completion of
3376 the collection all @CAF@s will have {\em return reference} info-tables
3377 again.
3378
3379 This is the scheme we adopt. A @CAF@ indirection has evacuation code
3380 which returns the evacuated and updated reference. During garbage
3381 collection, all the @CAF@s are overwritten with an internal @CAF@ info
3382 table which has evacuation code which performs this evacuate and
3383 update and restores the original @CAF@ code. At some point during the
3384 collection we must ensure that all the @CAF@s are indeed evacuated.
3385
3386 The only potential problem with this scheme is a cyclic list of @CAF@s
3387 all directly referencing (possibly via indirections) another @CAF@!
3388 Evacuation of the first @CAF@ will fail in an infinite loop of @CAF@
3389 evacuations. This is solved by ensuring that the @CAF@ info-table is
3390 updated to a {\em return reference} info-table before performing the
3391 evacuate and update. If this {\em return reference} evacuation code is
3392 called before the actual evacuation is complete it must be because
3393 such a cycle of references exists. Returning the still unevacuated
3394 reference is OK --- all the @CAF@s will now reference the same
3395 @CAF@ which will reference itself! Construction of such a structure
3396 indicates the program must be in an infinite loop.
3397
3398 {\bf Compacting Collector}
3399
3400 When shorting out a @CAF@, its reference must be marked. A first
3401 attempt might explicitly mark the @CAF@s, updating the reference with
3402 the marked reference (possibly short circuting indirections). The
3403 actual @CAF@ marking code can indicate that they have already been
3404 marked (though this might not have actually been done yet) and return
3405 the indirection pointer so it is shorted out. Unfortunately the @CAF@
3406 reference might point to an indirection which will be subsequently
3407 shorted out. Rather than returning the @CAF@ reference we treat the
3408 @CAF@ as an indirection, calling the mark code of the reference, which
3409 will return the appropriately shorted reference.
3410
3411 Problem: Cyclic list of @CAF@s all directly referencing (possibly via
3412 indirections) another @CAF@!
3413
3414 Before compacting, the locations of the @CAF@ references are
3415 explicitly linked to the closures they reference (if they reference
3416 heap allocated closures) so that the compacting process will update
3417 them to the closure's new location. Unfortunately these locations'
3418 @CAF@ indirections are static.  This causes premature termination
3419 since the test to find the info pointer at the end of the location
3420 list will match more than one value.  This can be solved by using an
3421 auxiliary dynamic array (on the top of the A stack).  One location for
3422 each @CAF@ indirection is linked to the closure that the @CAF@
3423 references. Once collection is complete this array is traversed and
3424 the corresponding @CAF@ is then updated with the updated pointer from
3425 the auxiliary array.
3426
3427
3428 It is possible to use an alternative marking scheme, using a similar
3429 idea to the copying solution. This scheme avoids the need to update
3430 the @CAF@ references explicitly. We introduce an auxillary {\em mark
3431 and update} @CAF@ info-table which is used to update all @CAF@s at the
3432 start of a collection. The new code marks the @CAF@ reference,
3433 updating it with the returned reference.  The returned reference is
3434 itself returned so the @CAF@ is shorted out.  The code also modifies the
3435 @CAF@ info-table to be a {\em return reference}.  Subsequent attempts to
3436 mark the @CAF@ simply return the updated reference.
3437
3438 A cyclic @CAF@ reference will result in an attempt to mark the @CAF@
3439 before the marking has been completed and the reference updated. We
3440 cannot start marking the @CAF@ as it is already being marked. Nor can
3441 we return the reference as it has not yet been updated. Neither can we
3442 treat the CAF as an indirection since the @CAF@ reference has been
3443 obscured by the pointer reversal stack. All we can do is return the
3444 @CAF@ itself. This will result in some @CAF@ references not being
3445 shorted out.
3446
3447 This scheme has not been adopted but has been implemented. The code is
3448 commented out with @#if 0@.
3449
3450 \subsection{The virtual register set}
3451
3452 We refer to any (atomic) part of the virtual machine state as a ``register.''
3453 These ``registers'' may be shared between all threads in the system or may be
3454 specific to each thread.
3455
3456 Global: 
3457 @
3458   Hp
3459   HpLim
3460   Thread preemption flag
3461 @
3462
3463 Thread specific:
3464 @
3465   TSO - pointer to the TSO for when we have to pack thread away
3466   Sp
3467   SpLim
3468   Su - used to calculate number of arguments on stack
3469      - this is a more convenient representation
3470   Call/return registers (aka General purpose registers)
3471   Cost centre (and other debug/profile info)
3472   Statistic gathering (not in production system)
3473   Exception handlers 
3474     Heap overflow  - possible global?
3475     Stack overflow - possibly global?
3476     Pattern match failure
3477     maybe a failWith handler?
3478     maybe an exitWith handler?
3479     ...
3480 @
3481
3482 Some of these virtual ``registers'' are used very frequently and should
3483 be mapped onto machine registers if at all possible.  Others are used
3484 very infrequently and can be kept in memory to free up registers for
3485 other uses.
3486
3487 On register-poor architectures, we can play a few tricks to reduce the
3488 number of virtual registers which need to be accessed on a regular
3489 basis:
3490
3491 @
3492 - HpLim trick
3493 - Grow stack and heap towards each other (single-threaded system only)
3494 - We might need to keep the C stack pointer in a register if that
3495   is what the OS expects when a signal occurs.
3496 - Preemption flag trick
3497 - If any of the frequently accessed registers cannot be mapped onto
3498   machine registers we should keep the TSO in a machine register to
3499   allow faster access to all the other non-machine registers.
3500 @
3501
3502
3503 \end{document}
3504
3505