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