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