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