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