Debian Codegraph @

doc/guide/src/MLtonContIsolateImplementation.adoc

raw
1 = MLtonContIsolateImplementation
2
3 As noted before, it is fairly easy to get the operational behavior of `isolate` with just `callcc` and `throw`, but establishing the right space behavior is trickier. Here, we show how to start from the obvious, but inefficient, implementation of `isolate` using only `callcc` and `throw`, and 'derive' an equivalent, but more efficient, implementation of `isolate` using MLton's primitive stack capture and copy operations. This isn't a formal derivation, as we are not formally showing the equivalence of the programs (though I believe that they are all equivalent, modulo the space behavior).
4
5 Here is a direct implementation of isolate using only `callcc` and `throw`:
6
7 [source,sml]
8 ----
9 val isolate: ('a -> unit) -> 'a t =
10 fn (f: 'a -> unit) =>
11 callcc
12 (fn k1 =>
13 let
14 val x = callcc (fn k2 => throw (k1, k2))
15 val _ = (f x ; Exit.topLevelSuffix ())
16 handle exn => MLtonExn.topLevelHandler exn
17 in
18 raise Fail "MLton.Cont.isolate: return from (wrapped) func"
19 end)
20 ----
21
22
23 We use the standard nested `callcc` trick to return a continuation that is ready to receive an argument, execute the isolated function, and exit the program. Both `Exit.topLevelSuffix` and `MLtonExn.topLevelHandler` will terminate the program.
24
25 Throwing to an isolated function will execute the function in a 'semantically' empty context, in the sense that we never re-execute the 'original' continuation of the call to isolate (i.e., the context that was in place at the time `isolate` was called). However, we assume that the compiler isn't able to recognize that the 'original' continuation is unused; for example, while we (the programmer) know that `Exit.topLevelSuffix` and `MLtonExn.topLevelHandler` will terminate the program, the compiler may only see opaque calls to unknown foreign-functions. So, that original continuation (in its entirety) is part of the continuation returned by `isolate` and throwing to the continuation returned by `isolate` will execute `f x` (with the exit wrapper) in the context of that original continuation. Thus, the garbage collector will retain everything reachable from that original continuation during the evaluation of `f x`, even though it is 'semantically' garbage.
26
27 Note that this space-leak is independent of the implementation of continuations (it arises in both MLton's stack copying implementation of continuations and would arise in SML/NJ's CPS-translation implementation); we are only assuming that the implementation can't 'see' the program termination, and so must retain the original continuation (and anything reachable from it).
28
29 So, we need an 'empty' continuation in which to execute `f x`. (No surprise there, as that is the written description of `isolate`.) To do this, we capture a top-level continuation and throw to that in order to execute `f x`:
30
31 [source,sml]
32 ----
33 local
34 val base: (unit -> unit) t =
35 callcc
36 (fn k1 =>
37 let
38 val th = callcc (fn k2 => throw (k1, k2))
39 val _ = (th () ; Exit.topLevelSuffix ())
40 handle exn => MLtonExn.topLevelHandler exn
41 in
42 raise Fail "MLton.Cont.isolate: return from (wrapped) func"
43 end)
44 in
45 val isolate: ('a -> unit) -> 'a t =
46 fn (f: 'a -> unit) =>
47 callcc
48 (fn k1 =>
49 let
50 val x = callcc (fn k2 => throw (k1, k2))
51 in
52 throw (base, fn () => f x)
53 end)
54 end
55 ----
56
57
58 We presume that `base` is evaluated 'early' in the program. There is a subtlety here, because one needs to believe that this `base` continuation (which technically corresponds to the entire rest of the program evaluation) 'works' as an empty context; in particular, we want it to be the case that executing `f x` in the `base` context retains less space than executing `f x` in the context in place at the call to `isolate` (as occurred in the previous implementation of `isolate`). This isn't particularly easy to believe if one takes a normal substitution-based operational semantics, because it seems that the context captured and bound to `base` is arbitrarily large. However, this context is mostly unevaluated code; the only heap-allocated values that are reachable from it are those that were evaluated before the evaluation of `base` (and used in the program after the evaluation of `base`). Assuming that `base` is evaluated 'early' in the program, we conclude that there are few heap-allocated values reachable from its continuation. In contrast, the previous implementation of `isolate` could capture a context that has many heap-allocated values reachable from it (because we could evaluate `isolate f` 'late' in the program and 'deep' in a call stack), which would all remain reachable during the evaluation of
59 `f x`. [We'll return to this point later, as it is taking a slightly MLton-esque view of the evaluation of a program, and may not apply as strongly to other implementations (e.g., SML/NJ).]
60
61 Now, once we throw to `base` and begin executing `f x`, only the heap-allocated values reachable from `f` and `x` and the few heap-allocated values reachable from `base` are retained by the garbage collector. So, it seems that `base` 'works' as an empty context.
62
63 But, what about the continuation returned from `isolate f`? Note that the continuation returned by `isolate` is one that receives an argument `x` and then
64 throws to `base` to evaluate `f x`. If we used a CPS-translation implementation (and assume sufficient beta-contractions to eliminate administrative redexes), then the original continuation passed to `isolate` (i.e., the continuation bound to `k1`) will not be free in the continuation returned by `isolate f`. Rather, the only free variables in the continuation returned by `isolate f` will be `base` and `f`, so the only heap-allocated values reachable from the continuation returned by `isolate f` will be those values reachable from `base` (assumed to be few) and those values reachable from `f` (necessary in order to execute `f` at some later point).
65
66 But, MLton doesn't use a CPS-translation implementation. Rather, at each call to `callcc` in the body of `isolate`, MLton will copy the current execution stack. Thus, `k2` (the continuation returned by `isolate f`) will include execution stack at the time of the call to `isolate f` -- that is, it will include the 'original' continuation of the call to `isolate f`. Thus, the heap-allocated values reachable from the continuation returned by `isolate f` will include those values reachable from `base`, those values reachable from `f`, and those values reachable from the original continuation of the call to `isolate f`. So, just holding on to the continuation returned by `isolate f` will retain all of the heap-allocated values live at the time `isolate f` was called. This leaks space, since, 'semantically', the
67 continuation returned by `isolate f` only needs the heap-allocated values reachable from `f` (and `base`).
68
69 In practice, this probably isn't a significant issue. A common use of `isolate` is implement `abort`:
70 [source,sml]
71 ----
72 fun abort th = throw (isolate th, ())
73 ----
74
75 The continuation returned by `isolate th` is dead immediately after being thrown to -- the continuation isn't retained, so neither is the 'semantic'
76 garbage it would have retained.
77
78 But, it is easy enough to 'move' onto the 'empty' context `base` the capturing of the context that we want to be returned by `isolate f`:
79
80 [source,sml]
81 ----
82 local
83 val base: (unit -> unit) t =
84 callcc
85 (fn k1 =>
86 let
87 val th = callcc (fn k2 => throw (k1, k2))
88 val _ = (th () ; Exit.topLevelSuffix ())
89 handle exn => MLtonExn.topLevelHandler exn
90 in
91 raise Fail "MLton.Cont.isolate: return from (wrapped) func"
92 end)
93 in
94 val isolate: ('a -> unit) -> 'a t =
95 fn (f: 'a -> unit) =>
96 callcc
97 (fn k1 =>
98 throw (base, fn () =>
99 let
100 val x = callcc (fn k2 => throw (k1, k2))
101 in
102 throw (base, fn () => f x)
103 end))
104 end
105 ----
106
107
108 This implementation now has the right space behavior; the continuation returned by `isolate f` will only retain the heap-allocated values reachable from `f` and from `base`. (Technically, the continuation will retain two copies of the stack that was in place at the time `base` was evaluated, but we are assuming that that stack small.)
109
110 One minor inefficiency of this implementation (given MLton's implementation of continuations) is that every `callcc` and `throw` entails copying a stack (albeit, some of them are small). We can avoid this in the evaluation of `base` by using a reference cell, because `base` is evaluated at the top-level:
111
112 [source,sml]
113 ----
114 local
115 val base: (unit -> unit) option t =
116 let
117 val baseRef: (unit -> unit) option t option ref = ref NONE
118 val th = callcc (fn k => (base := SOME k; NONE))
119 in
120 case th of
121 NONE => (case !baseRef of
122 NONE => raise Fail "MLton.Cont.isolate: missing base"
123 | SOME base => base)
124 | SOME th => let
125 val _ = (th () ; Exit.topLevelSuffix ())
126 handle exn => MLtonExn.topLevelHandler exn
127 in
128 raise Fail "MLton.Cont.isolate: return from (wrapped)
129 func"
130 end
131 end
132 in
133 val isolate: ('a -> unit) -> 'a t =
134 fn (f: 'a -> unit) =>
135 callcc
136 (fn k1 =>
137 throw (base, SOME (fn () =>
138 let
139 val x = callcc (fn k2 => throw (k1, k2))
140 in
141 throw (base, SOME (fn () => f x))
142 end)))
143 end
144 ----
145
146
147 Now, to evaluate `base`, we only copy the stack once (instead of 3 times). Because we don't have a dummy continuation around to initialize the reference cell, the reference cell holds a continuation `option`. To distinguish between the original evaluation of `base` (when we want to return the continuation) and the subsequent evaluations of `base` (when we want to evaluate a thunk), we capture a `(unit \-> unit) option` continuation.
148
149 This seems to be as far as we can go without exploiting the concrete implementation of continuations in <<MLtonCont#>>. Examining the implementation, we note that the type of
150 continuations is given by
151 [source,sml]
152 ----
153 type 'a t = (unit -> 'a) -> unit
154 ----
155
156 and the implementation of `throw` is given by
157 [source,sml]
158 ----
159 fun ('a, 'b) throw' (k: 'a t, v: unit -> 'a): 'b =
160 (k v; raise Fail "MLton.Cont.throw': return from continuation")
161
162 fun ('a, 'b) throw (k: 'a t, v: 'a): 'b = throw' (k, fn () => v)
163 ----
164
165
166 Suffice to say, a continuation is simply a function that accepts a thunk to yield the thrown value and the body of the function performs the actual throw. Using this knowledge, we can create a dummy continuation to initialize `baseRef` and greatly simplify the body of `isolate`:
167
168 [source,sml]
169 ----
170 local
171 val base: (unit -> unit) option t =
172 let
173 val baseRef: (unit -> unit) option t ref =
174 ref (fn _ => raise Fail "MLton.Cont.isolate: missing base")
175 val th = callcc (fn k => (baseRef := k; NONE))
176 in
177 case th of
178 NONE => !baseRef
179 | SOME th => let
180 val _ = (th () ; Exit.topLevelSuffix ())
181 handle exn => MLtonExn.topLevelHandler exn
182 in
183 raise Fail "MLton.Cont.isolate: return from (wrapped)
184 func"
185 end
186 end
187 in
188 val isolate: ('a -> unit) -> 'a t =
189 fn (f: 'a -> unit) =>
190 fn (v: unit -> 'a) =>
191 throw (base, SOME (f o v))
192 end
193 ----
194
195
196 Note that this implementation of `isolate` makes it clear that the continuation returned by `isolate f` only retains the heap-allocated values reachable from `f` and `base`. It also retains only one copy of the stack that was in place at the time `base` was evaluated. Finally, it completely avoids making any copies of the stack that is in place at the time `isolate f` is evaluated; indeed, `isolate f` is a constant-time operation.
197
198 Next, suppose we limited ourselves to capturing `unit` continuations with `callcc`. We can't pass the thunk to be evaluated in the 'empty' context directly, but we can use a reference cell.
199
200 [source,sml]
201 ----
202 local
203 val thRef: (unit -> unit) option ref = ref NONE
204 val base: unit t =
205 let
206 val baseRef: unit t ref =
207 ref (fn _ => raise Fail "MLton.Cont.isolate: missing base")
208 val () = callcc (fn k => baseRef := k)
209 in
210 case !thRef of
211 NONE => !baseRef
212 | SOME th =>
213 let
214 val _ = thRef := NONE
215 val _ = (th () ; Exit.topLevelSuffix ())
216 handle exn => MLtonExn.topLevelHandler exn
217 in
218 raise Fail "MLton.Cont.isolate: return from (wrapped) func"
219 end
220 end
221 in
222 val isolate: ('a -> unit) -> 'a t =
223 fn (f: 'a -> unit) =>
224 fn (v: unit -> 'a) =>
225 let
226 val () = thRef := SOME (f o v)
227 in
228 throw (base, ())
229 end
230 end
231 ----
232
233
234 Note that it is important to set `thRef` to `NONE` before evaluating the thunk, so that the garbage collector doesn't retain all the heap-allocated values reachable from `f` and `v` during the evaluation of `f (v ())`. This is because `thRef` is still live during the evaluation of the thunk; in particular, it was allocated before the evaluation of `base` (and used after), and so is retained by continuation on which the thunk is evaluated.
235
236 This implementation can be easily adapted to use MLton's primitive stack copying operations.
237
238 [source,sml]
239 ----
240 local
241 val thRef: (unit -> unit) option ref = ref NONE
242 val base: Thread.preThread =
243 let
244 val () = Thread.copyCurrent ()
245 in
246 case !thRef of
247 NONE => Thread.savedPre ()
248 | SOME th =>
249 let
250 val () = thRef := NONE
251 val _ = (th () ; Exit.topLevelSuffix ())
252 handle exn => MLtonExn.topLevelHandler exn
253 in
254 raise Fail "MLton.Cont.isolate: return from (wrapped) func"
255 end
256 end
257 in
258 val isolate: ('a -> unit) -> 'a t =
259 fn (f: 'a -> unit) =>
260 fn (v: unit -> 'a) =>
261 let
262 val () = thRef := SOME (f o v)
263 val new = Thread.copy base
264 in
265 Thread.switchTo new
266 end
267 end
268 ----
269
270
271 In essence, `Thread.copyCurrent` copies the current execution stack and stores it in an implicit reference cell in the runtime system, which is fetchable with `Thread.savedPre`. When we are ready to throw to the isolated function, `Thread.copy` copies the saved execution stack (because the stack is modified in place during execution, we need to retain a pristine copy in case the isolated function itself throws to other isolated functions) and `Thread.switchTo` abandons the current execution stack, installing the newly copied execution stack.
272
273 The actual implementation of `MLton.Cont.isolate` simply adds some `Thread.atomicBegin` and `Thread.atomicEnd` commands, which effectively protect the global `thRef` and accommodate the fact that `Thread.switchTo` does an implicit `Thread.atomicEnd` (used for leaving a signal handler thread).
274
275 [source,sml]
276 ----
277 local
278 val thRef: (unit -> unit) option ref = ref NONE
279 val base: Thread.preThread =
280 let
281 val () = Thread.copyCurrent ()
282 in
283 case !thRef of
284 NONE => Thread.savedPre ()
285 | SOME th =>
286 let
287 val () = thRef := NONE
288 val _ = MLton.atomicEnd (* Match 1 *)
289 val _ = (th () ; Exit.topLevelSuffix ())
290 handle exn => MLtonExn.topLevelHandler exn
291 in
292 raise Fail "MLton.Cont.isolate: return from (wrapped) func"
293 end
294 end
295 in
296 val isolate: ('a -> unit) -> 'a t =
297 fn (f: 'a -> unit) =>
298 fn (v: unit -> 'a) =>
299 let
300 val _ = MLton.atomicBegin (* Match 1 *)
301 val () = thRef := SOME (f o v)
302 val new = Thread.copy base
303 val _ = MLton.atomicBegin (* Match 2 *)
304 in
305 Thread.switchTo new (* Match 2 *)
306 end
307 end
308 ----
309
310
311 It is perhaps interesting to note that the above implementation was originally 'derived' by specializing implementations of the <<MLtonThread#>> `new`, `prepare`, and `switch` functions as if their only use was in the following implementation of `isolate`:
312
313 [source,sml]
314 ----
315 val isolate: ('a -> unit) -> 'a t =
316 fn (f: 'a -> unit) =>
317 fn (v: unit -> 'a) =>
318 let
319 val th = (f (v ()) ; Exit.topLevelSuffix ())
320 handle exn => MLtonExn.topLevelHandler exn
321 val t = MLton.Thread.prepare (MLton.Thread.new th, ())
322 in
323 MLton.Thread.switch (fn _ => t)
324 end
325 ----
326
327
328 It was pleasant to discover that it could equally well be 'derived' starting from the `callcc` and `throw` implementation.
329
330 As a final comment, we noted that the degree to which the context of `base` could be considered 'empty' (i.e., retaining few heap-allocated values) depended upon a slightly MLton-esque view. In particular, MLton does not heap allocate executable code. So, although the `base` context keeps a lot of unevaluated code 'live', such code is not heap allocated. In a system like SML/NJ, that does heap allocate executable code, one might want it to be the case that after throwing to an isolated function, the garbage collector retains only the code necessary to evaluate the function, and not any code that was necessary to evaluate the `base` context.