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