Home My Page Projects Code Snippets Project Openings SML/NJ
Summary Activity Forums Tracker Lists Tasks Docs Surveys News SCM Files

SCM Repository

[smlnj] Annotation of /sml/trunk/src/compiler/FLINT/opt/fcontract.sml
ViewVC logotype

Annotation of /sml/trunk/src/compiler/FLINT/opt/fcontract.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 190 - (view) (download)

1 : monnier 121 (* copyright 1998 YALE FLINT PROJECT *)
2 : monnier 159 (* monnier@cs.yale.edu *)
3 : monnier 121
4 :     signature FCONTRACT =
5 :     sig
6 :    
7 :     (* needs Collect to be setup properly *)
8 : monnier 190 val contract : FLINT.prog * Stats.counter -> FLINT.prog
9 : monnier 121
10 :     end
11 :    
12 :     (* All kinds of beta-reductions. In order to do as much work per pass as
13 :     * possible, the usage counts of each variable (maintained by the Collect
14 :     * module) is kept as much uptodate as possible. For instance as soon as a
15 :     * variable becomes dead, all the variables that were referenced have their
16 :     * usage counts decremented correspondingly. This means that we have to
17 :     * be careful to make sure that a dead variable will indeed not appear
18 :     * in the output lexp since it might else reference other dead variables *)
19 :    
20 : monnier 159 (* things that fcontract does:
21 :     * - several things not mentioned
22 :     * - elimination of Con(Decon x)
23 :     * - update counts when selecting a SWITCH alternative
24 : monnier 162 * - contracting RECORD(R.1,R.2) => R (only if the type is easily available)
25 : monnier 184 * - dropping of dead arguments
26 :     * - elimination of constant arguments
27 : monnier 159 *)
28 :    
29 : monnier 121 (* things that lcontract.sml does that fcontract doesn't do (yet):
30 : monnier 159 * - inline across DeBruijn depths (will be solved by named-tvar)
31 : monnier 121 * - elimination of let [dead-vs] = pure in body
32 :     *)
33 :    
34 :     (* things that cpsopt/eta.sml did that fcontract doesn't do:
35 : monnier 159 * - let f vs = select(v,i,g,g vs)
36 : monnier 121 *)
37 :    
38 :     (* things that cpsopt/contract.sml did that fcontract doesn't do:
39 : monnier 159 * - IF-idiom (I still don't know what it is)
40 : monnier 121 * - unifying branches
41 :     * - Handler operations
42 :     * - primops expressions
43 :     * - branch expressions
44 :     *)
45 :    
46 :     (* things that could also be added:
47 : monnier 184 * - elimination of dead vars in let
48 : monnier 121 *)
49 :    
50 :     (* things that would require some type info:
51 :     * - dropping foo in LET vs = RAISE v IN foo
52 :     *)
53 :    
54 :     (* eta-reduction is tricky:
55 :     * - recognition of eta-redexes and introduction of the corresponding
56 :     * substitution in the table has to be done at the very beginning of
57 :     * the processing of the FIX
58 :     * - eta-reduction can turn a known function into an escaping function
59 :     * - fun f (g,v2,v3) = g(g,v2,v3) looks tremendously like an eta-redex
60 :     *)
61 :    
62 :     (* order of contraction is important:
63 :     * - the body of a FIX is contracted before the functions because the
64 :     * functions might end up being inlined in the body in which case they
65 :     * could be contracted twice.
66 :     *)
67 :    
68 :     (* When creating substitution f->g (as happens with eta redexes or with
69 :     * code like `LET [f] = RET[g]'), we need to make sure that the usage cout
70 :     * of f gets properly transfered to g. One way to do that is to make the
71 :     * transfer incremental: each time we apply the substitution, we decrement
72 :     * f's count and increment g's count. But this can be tricky since the
73 :     * elimination of the eta-redex (or the trivial binding) eliminates one of the
74 : monnier 159 * references to g and if this is the only one, we might trigger the killing
75 : monnier 121 * of g even though its count would be later incremented. Similarly, inlining
76 :     * of g would be dangerous as long as some references to f exist.
77 :     * So instead we do the transfer once and for all when we see the eta-redex,
78 :     * which frees us from those two problems but forces us to make sure that
79 :     * every existing reference to f will be substituted with g.
80 :     * Also, the transfer of counts from f to g is not quite straightforward
81 :     * since some of the references to f might be from inside g and without doing
82 :     * the transfer incrementally, we can't easily know which of the usage counts
83 :     * of f should be transfered to the internal counts of g and which to the
84 :     * external counts.
85 :     *)
86 :    
87 : monnier 159 (* Preventing infinite inlining:
88 :     * - inlining a function in its own body amounts to unrolling which has
89 :     * to be controlled (you only want to unroll some number of times).
90 :     * It's currently simply not allowed.
91 :     * - inlining a recursive function outside of tis body amounts to `peeling'
92 :     * one iteration. Here also, since the inlined body will have yet another
93 :     * call, the inlining risks non-termination. It's hence also
94 :     * not allowed.
95 :     * - inlining a mutually recursive function is just a more general form
96 :     * of the problem above although it can be safe and desirable in some cases.
97 :     * To be safe, you simply need that one of the functions forming the
98 :     * mutual-recursion loop cannot be inlined (to break the loop). This cannot
99 :     * be trivially checked. So we (foolishly?) trust the `inline' bit in
100 :     * those cases. This is mostly used to inline wrappers inside the
101 :     * function they wrap.
102 :     * - even if one only allows inlining of funtions showing no sign of
103 :     * recursion, we can be bitten by a program creating its own Y combinator:
104 :     * datatype dt = F of dt -> int -> int
105 :     * let fun f (F g) x = g (F g) x in f (F f) end
106 :     * To solve this problem, `cexp' has an `ifs' parameter containing the set
107 :     * of funtions that we are inlining in order to detect (and break) cycles.
108 :     * - funnily enough, if we allow inlining recursive functions the cycle
109 :     * detection will ensure that the unrolling (or peeling) will only be done
110 :     * once. In the future, maybe.
111 :     *)
112 :    
113 : monnier 184 (* Dropping useless arguments.
114 :     * Arguments whose value is constant (i.e. the function is known and each
115 :     * call site provides the same value for that argument (or the argument
116 :     * itself in the case of recursive calls) can be safely removed and replaced
117 :     * inside the body by a simple let binding. The only problem is that the
118 :     * constant argument might be out of scope at the function definition site.
119 :     * It is obviously always possible to move the function to bring the argument
120 :     * in scope, but since we don't do any code motion here, we're stuck.
121 :     * If it wasn't for this little problem, we could do the cst-arg removal in
122 :     * collect (we don't gain anything from doing it here).
123 :     * The removal of dead arguments (args not used in the body) on the other
124 :     * hand can quite well be done in collect, the only problem being that it
125 :     * is convenient to do it after the cst-arg removal so that we can rely
126 :     * on deadarg to do the actual removal of the cst-arg.
127 :     *)
128 :    
129 : monnier 121 (* Simple inlining (inlining called-once functions, which doesn't require
130 :     * alpha-renaming) seems inoffensive enough but is not always desirable.
131 : monnier 159 * The typical example is wrapper functions introduced by eta-expand: they
132 :     * usually (until inlined) contain the only call to the main function,
133 : monnier 121 * but inlining the main function in the wrapper defeats the purpose of the
134 :     * wrapper.
135 :     * cpsopt dealt with this problem by adding a `NO_INLINE_INTO' hint to the
136 : monnier 159 * wrapper function. In this file, the idea is the following:
137 :     * If you have a function declaration like `let f x = body in exp', first
138 :     * contract `exp' and only contract `body' afterwards. This ensures that
139 :     * the eta-wrapper gets a chance to be inlined before it is (potentially)
140 :     * eta-reduced away. Interesting details:
141 : monnier 121 * - all functions (even the ones that would have a `NO_INLINE_INTO') are
142 :     * contracted, because the "aggressive usage count maintenance" makes any
143 :     * alternative painful (the collect phase has already assumed that dead code
144 :     * will be eliminated, which means that fcontract should at the very least
145 : monnier 159 * do the dead-code elimination, so you can only avoid fcontracting a
146 :     * a function if you can be sure that the body doesn't contain any dead-code,
147 :     * which is generally not known).
148 : monnier 190 * - once a function is fcontracted, its inlinable status is re-examined.
149 :     * More specifically, if no inlining occured during its fcontraction, then
150 :     * we assume that the code has just become smaller and should hence
151 :     * still be considered inlinable. On another hand, if inlining took place,
152 :     * then we have to reset the inline-bit because the new body might
153 :     * be completely different (i.e. much bigger) and inlining it might be
154 :     * undesirable.
155 : monnier 159 * This means that in the case of
156 :     * let fwrap x = body1 and f y = body2 in exp
157 : monnier 190 * if fwrap is fcontracted before f and something gets inlined into it,
158 :     * then fwrap cannot be inlined in f.
159 : monnier 159 * To minimize the impact of this problem, we make sure that we fcontract
160 :     * inlinable functions only after fcontracting other mutually recursive
161 : monnier 190 * functions. One way to solve the problem more thoroughly would be
162 :     * to keep the uncontracted fwrap around until f has been contracted.
163 :     * Such a trick hasn't seemed necessary yet.
164 : monnier 121 * - at the very end of the optimization phase, cpsopt had a special pass
165 :     * that ignored the `NO_INLINE_INTO' hint (since at this stage, inlining
166 :     * into it doesn't have any undesirable side effects any more). The present
167 :     * code doesn't need such a thing. On another hand, the cpsopt approach
168 :     * had the advantage of keeping the `inline' bit from one contract phase to
169 : monnier 159 * the next. If this ends up being important, one could add a global
170 : monnier 121 * "noinline" flag that could be set to true whenever fcontracting an
171 : monnier 159 * inlinable function (this would ensure that fcontracting such an inlinable
172 :     * function can only reduce its size, which would allow keeping the `inline'
173 :     * bit set after fcontracting).
174 : monnier 121 *)
175 :    
176 :     structure FContract :> FCONTRACT =
177 :     struct
178 :     local
179 :     structure F = FLINT
180 :     structure M = IntmapF
181 : monnier 159 structure S = IntSetF
182 : monnier 121 structure C = Collect
183 : monnier 184 structure O = Option
184 : monnier 121 structure DI = DebIndex
185 :     structure PP = PPFlint
186 : monnier 159 structure FU = FlintUtil
187 :     structure LT = LtyExtern
188 : monnier 163 structure OU = OptUtils
189 : monnier 159 structure CTRL = Control.FLINT
190 : monnier 121 in
191 :    
192 :     val say = Control.Print.say
193 :     fun bug msg = ErrorMsg.impossible ("FContract: "^msg)
194 :     fun buglexp (msg,le) = (say "\n"; PP.printLexp le; bug msg)
195 :     fun bugval (msg,v) = (say "\n"; PP.printSval v; bug msg)
196 :    
197 :     (* fun sayexn e = app say (map (fn s => s^" <- ") (SMLofNJ.exnHistory e)) *)
198 :    
199 :     fun ASSERT (true,_) = ()
200 :     | ASSERT (FALSE,msg) = bug ("assertion "^msg^" failed")
201 :    
202 : monnier 159 val cplv = LambdaVar.dupLvar
203 : monnier 121
204 :     datatype sval
205 :     = Val of F.value (* F.value should never be F.VAR lv *)
206 :     | Fun of F.lvar * F.lexp * (F.lvar * F.lty) list * F.fkind * DI.depth
207 :     | TFun of F.lvar * F.lexp * (F.tvar * F.tkind) list * DI.depth
208 : monnier 189 | Record of F.lvar * sval list
209 :     | Con of F.lvar * sval * F.dcon * F.tyc list
210 :     | Decon of F.lvar * sval * F.dcon * F.tyc list
211 :     | Select of F.lvar * sval * int
212 : monnier 121 | Var of F.lvar * F.lty option (* cop out case *)
213 :    
214 : monnier 159 fun sval2lty (Var(_,x)) = x
215 :     | sval2lty (Decon(_,_,(_,_,lty),tycs)) =
216 :     SOME(hd(#2 (LT.ltd_arrow (hd(LT.lt_inst(lty, tycs))))))
217 :     | sval2lty _ = NONE
218 : monnier 121
219 : monnier 159 fun tycs_eq ([],[]) = true
220 :     | tycs_eq (tyc1::tycs1,tyc2::tycs2) =
221 :     LT.tc_eqv(tyc1,tyc2) andalso tycs_eq(tycs1,tycs2)
222 :     | tycs_eq _ = false
223 : monnier 121
224 : monnier 189 fun click s c = (if !CTRL.misc = 1 then say s else (); Stats.addCounter c 1)
225 : monnier 185
226 : monnier 189 (* val c_inline = Stats.newCounter[] *)
227 :     (* val c_deadval = Stats.newCounter[] *)
228 :     (* val c_deadlexp = Stats.newCounter[] *)
229 :     (* val c_select = Stats.newCounter[] *)
230 :     (* val c_record = Stats.newCounter[] *)
231 :     (* val c_lacktype = Stats.newCounter[] *)
232 :     (* val c_con = Stats.newCounter[] *)
233 :     (* val c_switch = Stats.newCounter[] *)
234 :     (* val c_eta = Stats.newCounter[] *)
235 :     (* val c_etasplit = Stats.newCounter[] *)
236 :     (* val c_branch = Stats.newCounter[] *)
237 :     (* val c_dropargs = Stats.newCounter[] *)
238 : monnier 185
239 : monnier 189 fun contract (fdec as (_,f,_,_), counter) = let
240 :    
241 :     val c_dummy = Stats.newCounter[]
242 :     val c_miss = Stats.newCounter[]
243 :    
244 :     fun click_deadval () = (click "d" counter)
245 :     fun click_deadlexp () = (click "D" counter)
246 :     fun click_select () = (click "s" counter)
247 :     fun click_record () = (click "r" counter)
248 :     fun click_con () = (click "c" counter)
249 :     fun click_switch () = (click "s" counter)
250 :     fun click_eta () = (click "e" counter)
251 :     fun click_etasplit () = (click "E" counter)
252 :     fun click_branch () = (click "b" counter)
253 :     fun click_dropargs () = (click "a" counter)
254 :    
255 :     fun click_lacktype () = (click "t" c_miss)
256 :    
257 :     (* this counters is actually *used* by fcontract.
258 :     * It's not used just for statistics. *)
259 :     val c_inline = Stats.newCounter[counter]
260 :     (* val c_inline1 = Stats.newCounter[c_inline] *)
261 :     (* val c_inline2 = Stats.newCounter[c_inline] *)
262 :     (* val c_unroll = Stats.newCounter[c_inline] *)
263 :     fun click_simpleinline () = (click "i" c_inline)
264 :     fun click_copyinline () = (click "I" c_inline)
265 :     fun click_unroll () = (click "u" c_inline)
266 :     fun inline_count () = Stats.getCounter c_inline
267 :    
268 : monnier 159 (* cfg: is used for deBruijn renumbering when inlining at different depths
269 :     * ifs (inlined functions): records which functions we're currently inlining
270 :     * in order to detect loops
271 :     * m: is a map lvars to their defining expressions (svals) *)
272 : monnier 184 fun cexp (cfg as (d,od)) ifs m le cont = let
273 : monnier 159
274 :     val loop = cexp cfg ifs
275 :    
276 : monnier 186 fun used lv = (C.usenb(C.get lv) > 0)
277 :     handle x =>
278 :     (say("while in FContract.used "^(C.LVarString lv)^"\n");
279 :     raise x)
280 : monnier 121
281 :     fun impurePO po = true (* if a PrimOP is pure or not *)
282 :    
283 :     fun eqConV (F.INTcon i1, F.INT i2) = i1 = i2
284 :     | eqConV (F.INT32con i1, F.INT32 i2) = i1 = i2
285 :     | eqConV (F.WORDcon i1, F.WORD i2) = i1 = i2
286 :     | eqConV (F.WORD32con i1, F.WORD32 i2) = i1 = i2
287 :     | eqConV (F.REALcon r1, F.REAL r2) = r1 = r2
288 :     | eqConV (F.STRINGcon s1, F.STRING s2) = s1 = s2
289 :     | eqConV (con,v) = bugval("unexpected comparison with val", v)
290 :    
291 :     fun lookup m lv = (M.lookup m lv)
292 :     (* handle e as M.IntmapF =>
293 :     (say "\nlooking up unbound ";
294 :     say (!PP.LVarString lv);
295 :     raise e) *)
296 :    
297 :     fun sval2val sv =
298 :     case sv
299 : monnier 159 of (Fun{1=lv,...} | TFun{1=lv,...} | Record{1=lv,...} | Decon{1=lv,...}
300 : monnier 121 | Con{1=lv,...} | Select{1=lv,...} | Var{1=lv,...}) => F.VAR lv
301 :     | Val v => v
302 :    
303 : monnier 163 fun val2sval m (F.VAR ov) =
304 : monnier 189 ((lookup m ov) handle x =>
305 :     (say("val2sval "^(C.LVarString ov)^"\n"); raise x))
306 : monnier 121 | val2sval m v = Val v
307 :    
308 :     fun bugsv (msg,sv) = bugval(msg, sval2val sv)
309 :    
310 :     fun subst m ov = sval2val (lookup m ov)
311 :     val substval = sval2val o (val2sval m)
312 :     fun substvar lv =
313 :     case substval(F.VAR lv)
314 :     of F.VAR lv => lv
315 :     | v => bugval ("unexpected val", v)
316 :    
317 :     (* called when a variable becomes dead.
318 :     * it simply adjusts the use-counts *)
319 :     fun undertake m lv =
320 :     let val undertake = undertake m
321 :     in case lookup m lv
322 : monnier 186 of Var {1=nlv,...} => ()
323 : monnier 121 | Val v => ()
324 :     | Fun (lv,le,args,_,_) =>
325 : monnier 187 C.unuselexp undertake
326 :     (F.LET(map #1 args,
327 :     F.RET (map (fn _ => F.INT 0) args),
328 :     le))
329 :     | TFun{1=lv,2=le,...} =>
330 :     C.unuselexp undertake le
331 : monnier 189 | (Select {2=sv,...} | Con {2=sv,...}) => unusesval m sv
332 :     | Record {2=svs,...} => app (unusesval m) svs
333 : monnier 159 (* decon's are implicit so we can't get rid of them *)
334 :     | Decon _ => ()
335 : monnier 121 end
336 :     handle M.IntmapF =>
337 : monnier 186 (say("Unable to undertake "^(C.LVarString lv)^"\n"))
338 : monnier 121 | x =>
339 : monnier 186 (say("while undertaking "^(C.LVarString lv)^"\n"); raise x)
340 : monnier 121
341 : monnier 189 and unusesval m sv = unuseval m (sval2val sv)
342 : monnier 187 and unuseval m (F.VAR lv) =
343 :     if (C.unuse false (C.get lv)) then undertake m lv else ()
344 :     | unuseval f _ = ()
345 :     fun unusecall m lv =
346 :     if (C.unuse true (C.get lv)) then undertake m lv else ()
347 :    
348 :    
349 : monnier 121 fun addbind (m,lv,sv) = M.add(m, lv, sv)
350 :    
351 : monnier 164 (* substitute a value sv for a variable lv and unuse value v. *)
352 : monnier 121 fun substitute (m, lv1, sv, v) =
353 :     (case sval2val sv of F.VAR lv2 => C.transfer(lv1,lv2) | v2 => ();
354 : monnier 187 unuseval m v;
355 : monnier 121 addbind(m, lv1, sv)) handle x =>
356 : monnier 186 (say ("while substituting "^
357 : monnier 164 (C.LVarString lv1)^
358 :     " -> ");
359 : monnier 121 PP.printSval (sval2val sv);
360 :     raise x)
361 :    
362 :     (* common code for primops *)
363 :     fun cpo (SOME{default,table},po,lty,tycs) =
364 :     (SOME{default=substvar default,
365 :     table=map (fn (tycs,lv) => (tycs, substvar lv)) table},
366 :     po,lty,tycs)
367 :     | cpo po = po
368 :    
369 :     fun cdcon (s,Access.EXN(Access.LVAR lv),lty) =
370 :     (s, Access.EXN(Access.LVAR(substvar lv)), lty)
371 :     | cdcon dc = dc
372 :    
373 : monnier 184 fun zip ([],[]) = []
374 :     | zip (x::xs,y::ys) = (x,y)::(zip(xs,ys))
375 :     | zip _ = bug "bad zip"
376 : monnier 163
377 : monnier 159 (* F.APP inlining (if any)
378 :     * `ifs' is the set of function we are currently inlining
379 :     * `f' is the function, `vs' its arguments.
380 :     * return either (NONE, ifs) if inlining cannot be done or
381 :     * (SOME lexp, nifs) where `lexp' is the expansion of APP(f,vs) and
382 :     * `nifs' is the new set of functions we are currently inlining.
383 :     *)
384 :     fun inline ifs (f,vs) =
385 : monnier 121 case ((val2sval m f) handle x => raise x)
386 : monnier 184 of Fun(g,body,args,{inline,...},od) =>
387 : monnier 164 (ASSERT(used g, "used "^(C.LVarString g));
388 : monnier 184 if d <> od then (NONE, ifs)
389 : monnier 186 else if ((C.usenb(C.get g))handle x => raise x) = 1 andalso not(S.member ifs g) then
390 : monnier 121
391 : monnier 184 (* simple inlining: we should copy the body and then
392 :     * kill the function, but instead we just move the body
393 :     * and kill only the function name. This inlining strategy
394 :     * looks inoffensive enough, but still requires some care:
395 :     * see comments at the begining of this file and in cfun *)
396 : monnier 189 (click_simpleinline();
397 : monnier 187 ignore(C.unuse true (C.get g));
398 : monnier 184 ASSERT(not (used g), "killed");
399 :     (SOME(F.LET(map #1 args, F.RET vs, body), od), ifs))
400 : monnier 121
401 :     (* aggressive inlining (but hopefully safe). We allow
402 :     * inlining for mutually recursive functions (isrec)
403 :     * despite the potential risk. The reason is that it can
404 :     * happen that a wrapper (that should be inlined) has to be made
405 :     * mutually recursive with its main function. On another hand,
406 :     * self recursion (C.recursive) is too dangerous to be inlined
407 : monnier 184 * except for loop unrolling *)
408 : monnier 190 (* unrolling is not as straightforward as it seems:
409 :     * if you inline the function you're currently fcontracting,
410 :     * you're asking for trouble: there is a hidden assumption
411 :     * in the counting that the old code will be replaced by the new
412 :     * code (and is hence dead). If the function to be unrolled
413 :     * has the only call to function f, then f might get simpleinlined
414 :     * before unrolling, which means that unrolling will introduce
415 :     * a second occurence of the `only call' but at that point f
416 :     * has already been killed. *)
417 :     else if (inline = F.IH_ALWAYS andalso not(S.member ifs g)) (*orelse
418 :     (inline = F.IH_UNROLL andalso (S.member ifs g)) *) then
419 : monnier 163 let val nle =
420 : monnier 164 C.copylexp M.empty (F.LET(map #1 args, F.RET vs, body))
421 : monnier 184 in
422 :     (* say ("\nInlining "^(C.LVarString g)); *)
423 : monnier 187 (app (unuseval m) vs) handle x => raise x;
424 :     unusecall m g;
425 : monnier 184 (SOME(nle, od),
426 :     (* gross hack: to prevent further unrolling,
427 :     * I pretend that the rest is not inside the body *)
428 : monnier 189 if inline = F.IH_UNROLL
429 :     then (click_unroll(); S.rmv(g, ifs))
430 :     else (click_copyinline(); S.add(g, ifs)))
431 : monnier 121 end
432 : monnier 159 else (NONE, ifs))
433 :     | sv => (NONE, ifs)
434 : monnier 121 in
435 :     case le
436 : monnier 184 of F.RET vs => cont(m, F.RET(map substval vs) handle x => raise x)
437 : monnier 121
438 :     | F.LET (lvs,le,body) =>
439 : monnier 184 let fun clet () =
440 :     loop m le
441 :     (fn (m,F.RET vs) =>
442 : monnier 190 let fun simplesubst (lv,v,m) =
443 : monnier 184 let val sv = (val2sval m v) handle x => raise x
444 :     in substitute(m, lv, sv, sval2val sv)
445 :     end
446 : monnier 190 val nm = (ListPair.foldl simplesubst m (lvs, vs))
447 : monnier 184 in loop nm body cont
448 :     end
449 :     | (m,nle) =>
450 :     let val nm = (foldl (fn (lv,m) =>
451 :     addbind(m, lv, Var(lv, NONE)))
452 :     m lvs)
453 :     in case loop nm body cont
454 :     of F.RET vs => if vs = (map F.VAR lvs) then nle
455 :     else F.LET(lvs, nle, F.RET vs)
456 :     | nbody => F.LET(lvs, nle, nbody)
457 :     end)
458 : monnier 121 in case le
459 : monnier 184 of F.BRANCH (po,vs,le1,le2) =>
460 :     (* this is a hack originally meant to cleanup the BRANCH mess
461 :     * introduced in flintnm (where each branch returns just true or
462 :     * false which is generally only used as input to a SWITCH).
463 :     * The present code does slightly more than clean up this case *)
464 : monnier 121 let fun known (F.RECORD(_,_,_,le)) = known le
465 :     | known (F.CON(_,_,_,v,F.RET[F.VAR v'])) = (v = v')
466 :     | known (F.RET[F.VAR v]) = false
467 :     | known (F.RET[_]) = true
468 :     | known _ = false
469 : monnier 184 fun cassoc (lv,v,body,wrap) =
470 : monnier 186 if lv = v andalso ((C.usenb(C.get lv)) handle x=> raise x) = 1 andalso
471 : monnier 121 known le1 andalso known le2 then
472 :     (* here I should also check that le1 != le2 *)
473 :     let val nle1 = F.LET([lv], le1, body)
474 : monnier 159 val nlv = cplv lv
475 : monnier 164 val _ = C.new NONE nlv
476 :     val body2 = C.copylexp (M.add(M.empty, lv, nlv))
477 :     body
478 : monnier 121 val nle2 = F.LET([nlv], le2, body2)
479 : monnier 164 in
480 : monnier 189 click_branch();
481 : monnier 184 loop m (wrap(F.BRANCH(po, vs, nle1, nle2))) cont
482 : monnier 121 end
483 :     else
484 :     clet()
485 :     in case (lvs,body)
486 :     of ([lv],le as F.SWITCH(F.VAR v,_,_,NONE)) =>
487 : monnier 190 cassoc(lv, v, le, fn x => x)
488 : monnier 121 | ([lv],F.LET(lvs,le as F.SWITCH(F.VAR v,_,_,NONE),rest)) =>
489 : monnier 184 cassoc(lv, v, le, fn le => F.LET(lvs,le,rest))
490 : monnier 121 | _ => clet()
491 :     end
492 : monnier 184 | _ => clet()
493 : monnier 121 end
494 : monnier 184
495 : monnier 121 | F.FIX (fs,le) =>
496 : monnier 189 let (* The actual function contraction *)
497 : monnier 164 fun cfun (m,[]:F.fundec list,acc) = acc
498 : monnier 184 | cfun (m,fdec as ({inline,cconv,known,isrec},f,args,body)::fs,acc) =
499 : monnier 189 let val fi = C.get f
500 :     in if C.dead fi then cfun(m, fs, acc)
501 :     else if C.iusenb fi = C.usenb fi then
502 :     (* we need to be careful that undertake not be called
503 :     * recursively *)
504 :     (C.use NONE fi; undertake m f; cfun(m, fs, acc))
505 :     else
506 : monnier 164 let (* val _ = say ("\nEntering "^(C.LVarString f)) *)
507 : monnier 189 val saved_ic = inline_count()
508 : monnier 164 (* make up the bindings for args inside the body *)
509 : monnier 121 fun addnobind ((lv,lty),m) =
510 :     addbind(m, lv, Var(lv, SOME lty))
511 :     val nm = foldl addnobind m args
512 :     (* contract the body and create the resulting fundec *)
513 : monnier 184 val nbody = cexp cfg (S.add(f, ifs)) nm body #2
514 : monnier 185 (* if inlining took place, the body might be completely
515 :     * changed (read: bigger), so we have to reset the
516 :     * `inline' bit *)
517 : monnier 184 val nfk = {isrec=isrec, cconv=cconv,
518 : monnier 189 known=known orelse not(C.escaping fi),
519 :     inline=if inline_count() = saved_ic
520 :     then inline
521 :     else F.IH_SAFE}
522 : monnier 121 (* update the binding in the map. This step is not
523 :     * not just a mere optimization but is necessary
524 :     * because if we don't do it and the function
525 :     * gets inlined afterwards, the counts will reflect the
526 :     * new contracted code while we'll be working on the
527 :     * the old uncontracted code *)
528 :     val nm = addbind(m, f, Fun(f, nbody, args, nfk, od))
529 :     in cfun(nm, fs, (nfk, f, args, nbody)::acc)
530 : monnier 164 (* before say ("\nExiting "^(C.LVarString f)) *)
531 : monnier 121 end
532 : monnier 189 end
533 : monnier 121
534 :     (* check for eta redex *)
535 : monnier 186 fun ceta (fdec as (fk,f,args,F.APP(g,vs)):F.fundec,(m,fs,hs)) =
536 : monnier 121 if vs = (map (F.VAR o #1) args) andalso
537 :     (* don't forget to check that g is not one of the args
538 :     * and not f itself either *)
539 :     (List.find (fn v => v = g) (F.VAR f::vs)) = NONE
540 :     then
541 :     let val svg = val2sval m g
542 :     val g = case sval2val svg
543 :     of F.VAR g => g
544 :     | v => bugval("not a variable", v)
545 :     (* NOTE: we don't want to turn a known function into an
546 :     * escaping one. It's dangerous for optimisations based
547 :     * on known functions (elimination of dead args, f.ex)
548 :     * and could generate cases where call>use in collect *)
549 : monnier 189 in if (C.escaping(C.get f)) andalso not(C.escaping(C.get g))
550 :     (* the default case could ensure the inline *)
551 :     then (m, fdec::fs, hs)
552 :     else let
553 : monnier 121 (* if an earlier function h has been eta-reduced
554 :     * to f, we have to be careful to update its
555 :     * binding to not refer to f any more since f
556 :     * will disappear *)
557 :     val nm = foldl (fn (h,m) =>
558 :     if sval2val(lookup m h) = F.VAR f
559 :     then addbind(m, h, svg) else m)
560 :     m hs
561 : monnier 164 in
562 :     (* I could almost reuse `substitute' but the
563 :     * unuse in substitute assumes the val is escaping *)
564 : monnier 189 click_eta();
565 : monnier 164 C.transfer(f, g);
566 : monnier 187 unusecall m g;
567 : monnier 186 (addbind(m, f, svg), fs, f::hs)
568 : monnier 121 end
569 :     end
570 : monnier 186 else (m, fdec::fs, hs)
571 :     | ceta (fdec,(m,fs,hs)) = (m,fdec::fs,hs)
572 : monnier 121
573 : monnier 184 (* add wrapper for various purposes *)
574 :     fun wrap (f as ({inline=F.IH_ALWAYS,...},_,_,_):F.fundec,fs) = f::fs
575 :     | wrap (f as (fk as {isrec,...},g,args,body):F.fundec,fs) =
576 : monnier 189 let val gi = C.get g
577 :     fun dropargs filter =
578 : monnier 184 let val (nfk,nfk') = OU.fk_wrap(fk, O.map #1 isrec)
579 : monnier 164 val args' = filter args
580 : monnier 163 val ng = cplv g
581 :     val nargs = map (fn (v,t) => (cplv v, t)) args
582 : monnier 164 val nargs' = map #1 (filter nargs)
583 :     val appargs = (map F.VAR nargs')
584 : monnier 184 val nf = (nfk, g, nargs, F.APP(F.VAR ng, appargs))
585 : monnier 164 val nf' = (nfk', ng, args', body)
586 : monnier 186
587 :     val ngi = C.new (SOME(map #1 args')) ng
588 : monnier 184 in
589 : monnier 189 C.ireset gi;
590 :     app (ignore o (C.new NONE) o #1) nargs;
591 : monnier 186 C.use (SOME appargs) ngi;
592 : monnier 189 app (C.use NONE o C.get) nargs';
593 : monnier 184 nf'::nf::fs
594 : monnier 163 end
595 : monnier 190 in
596 : monnier 189 (* Don't introduce wrappers for escaping-only functions.
597 :     * This is debatable since although wrappers are useless
598 :     * on escaping-only functions, some of the escaping uses
599 :     * might turn into calls in the course of fcontract, so
600 :     * by not introducing wrappers here, we avoid useless work
601 :     * but we also postpone useful work to later invocations. *)
602 : monnier 190 if C.dead gi then fs else
603 :     let val used = map (used o #1) args
604 :     in if C.called gi then
605 :     (* if some args are not used, let's drop them *)
606 :     if not (List.all (fn x => x) used) then
607 :     (click_dropargs();
608 :     dropargs (fn xs => OU.filter(used, xs)))
609 :    
610 :     (* eta-split: add a wrapper for escaping uses *)
611 :     else if C.escaping gi then
612 :     (* like dropargs but keeping all args *)
613 :     (click_etasplit(); dropargs (fn x => x))
614 :    
615 :     else f::fs
616 :     else f::fs
617 :     end
618 : monnier 184 end
619 : monnier 163
620 : monnier 184 (* add various wrappers *)
621 :     val fs = foldl wrap [] fs
622 :    
623 : monnier 121 (* register the new bindings (uncontracted for now) *)
624 :     val nm = foldl (fn (fdec as (fk,f,args,body),m) =>
625 :     addbind(m, f, Fun(f, body, args, fk, od)))
626 :     m fs
627 :     (* check for eta redexes *)
628 : monnier 186 val (nm,fs,_) = foldl ceta (nm,[],[]) fs
629 : monnier 121
630 :     (* move the inlinable functions to the end of the list *)
631 :     val (f1s,f2s) =
632 : monnier 184 List.partition (fn ({inline=F.IH_ALWAYS,...},_,_,_) => true
633 : monnier 121 | _ => false) fs
634 :     val fs = f2s @ f1s
635 :    
636 :     (* contract the main body *)
637 : monnier 184 val nle = loop nm le cont
638 : monnier 121 (* contract the functions *)
639 :     val fs = cfun(nm, fs, [])
640 :     (* junk newly unused funs *)
641 :     val fs = List.filter (used o #2) fs
642 :     in
643 : monnier 163 case fs
644 :     of [] => nle
645 : monnier 184 | [f1 as ({isrec=NONE,...},_,_,_),f2] =>
646 : monnier 186 (* gross hack: `wrap' might have added a second
647 : monnier 163 * non-recursive function. we need to split them into
648 : monnier 184 * 2 FIXes. This is _very_ ad-hoc *)
649 : monnier 163 F.FIX([f2], F.FIX([f1], nle))
650 :     | _ => F.FIX(fs, nle)
651 : monnier 121 end
652 :    
653 :     | F.APP (f,vs) =>
654 :     let val nvs = ((map substval vs) handle x => raise x)
655 : monnier 159 in case inline ifs (f, nvs)
656 : monnier 190 of (SOME(le,od),nifs) => cexp (d,od) nifs m le cont
657 : monnier 184 | (NONE,_) => cont(m,F.APP((substval f) handle x => raise x, nvs))
658 : monnier 121 end
659 :    
660 :     | F.TFN ((f,args,body),le) =>
661 : monnier 189 let val fi = C.get f
662 :     in if C.dead fi then (click_deadlexp(); loop m le cont) else
663 : monnier 186 let val nbody = cexp (DI.next d, DI.next od) ifs m body #2
664 :     val nm = addbind(m, f, TFun(f, nbody, args, od))
665 :     val nle = loop nm le cont
666 :     in
667 : monnier 189 if C.dead fi then nle else F.TFN((f, args, nbody), nle)
668 : monnier 186 end
669 : monnier 189 end
670 : monnier 121
671 : monnier 184 | F.TAPP(f,tycs) =>
672 : monnier 189 (* (case val2sval m f
673 :     of TFun(g,body,args,od) =>
674 :     if d = od andalso C.usenb(C.get g) = 1 then
675 :     let val (_,_,_,le) =
676 :     ({inline=false,isrec=NONE,known=false,cconv=F.CC_FCT},
677 :     LV.mkLvar(),[],
678 :     F.TFN((g,args,body),TAPP(g,tycs)))
679 :     in
680 :     inlineWitness := true;
681 :     ignore(C.unuse true (C.get g));
682 :     end *)
683 : monnier 184 cont(m, F.TAPP((substval f) handle x => raise x, tycs))
684 : monnier 121
685 :     | F.SWITCH (v,ac,arms,def) =>
686 :     (case ((val2sval m v) handle x => raise x)
687 : monnier 189 of sv as Con (lvc,svc,dc1,tycs1) =>
688 : monnier 187 let fun killle le = C.unuselexp (undertake m) le
689 : monnier 159 fun kill lv le =
690 : monnier 187 C.unuselexp (undertake (addbind(m,lv,Var(lv,NONE)))) le
691 : monnier 159 fun killarm (F.DATAcon(_,_,lv),le) = kill lv le
692 :     | killarm _ = buglexp("bad arm in switch(con)", le)
693 :    
694 :     fun carm ((F.DATAcon(dc2,tycs2,lv),le)::tl) =
695 : monnier 185 (* sometimes lty1 <> lty2 :-( so this doesn't work:
696 :     * FU.dcon_eq(dc1, dc2) andalso tycs_eq(tycs1,tycs2) *)
697 :     if #2 dc1 = #2 (cdcon dc2) then
698 : monnier 159 (map killarm tl; (* kill the rest *)
699 : monnier 185 O.map killle def; (* and the default case *)
700 : monnier 189 loop (substitute(m, lv, svc, F.VAR lvc))
701 : monnier 184 le cont)
702 : monnier 159 else
703 :     (* kill this arm and continue with the rest *)
704 :     (kill lv le; carm tl)
705 : monnier 185 | carm [] = loop m (O.valOf def) cont
706 : monnier 121 | carm _ = buglexp("unexpected arm in switch(con,...)", le)
707 : monnier 189 in click_switch(); carm arms
708 : monnier 121 end
709 :    
710 : monnier 185 | sv as Val v =>
711 : monnier 187 let fun kill le = C.unuselexp (undertake m) le
712 : monnier 159 fun carm ((con,le)::tl) =
713 :     if eqConV(con, v) then
714 : monnier 184 (map (kill o #2) tl;
715 : monnier 185 O.map kill def;
716 : monnier 184 loop m le cont)
717 : monnier 159 else (kill le; carm tl)
718 : monnier 185 | carm [] = loop m (O.valOf def) cont
719 : monnier 189 in click_switch(); carm arms
720 : monnier 121 end
721 : monnier 185
722 :     | sv as (Var{1=lvc,...} | Select{1=lvc,...} | Decon{1=lvc, ...}
723 :     | (* will probably never happen *) Record{1=lvc,...}) =>
724 :     (case (arms,def)
725 :     of ([(F.DATAcon(dc,tycs,lv),le)],NONE) =>
726 :     (* this is a mere DECON, so we can push the let binding
727 :     * (hidden in cont) inside and maybe even drop the DECON *)
728 :     let val ndc = cdcon dc
729 : monnier 189 val slv = Decon(lv, sv, ndc, tycs)
730 :     val nm = addbind(m, lv, slv)
731 : monnier 185 (* see below *)
732 : monnier 189 val nm = addbind(nm, lvc, Con(lvc, slv, ndc, tycs))
733 : monnier 185 val nle = loop nm le cont
734 :     val nv = sval2val sv
735 :     in
736 :     if used lv then
737 :     F.SWITCH(nv,ac,[(F.DATAcon(ndc,tycs,lv),nle)],NONE)
738 : monnier 187 else (unuseval m nv; nle)
739 : monnier 185 end
740 :     | (([(_,le)],NONE) | ([],SOME le)) =>
741 :     (* This should never happen, but we can optimize it away *)
742 : monnier 189 (unuseval m (sval2val sv); loop m le cont)
743 : monnier 185 | _ =>
744 :     let fun carm (F.DATAcon(dc,tycs,lv),le) =
745 :     let val ndc = cdcon dc
746 : monnier 189 val slv = Decon(lv, sv, ndc, tycs)
747 :     val nm = addbind(m, lv, slv)
748 : monnier 185 (* we can rebind lv to a more precise value
749 :     * !!BEWARE!! This rebinding is misleading:
750 :     * - it gives the impression that `lvc' is built
751 :     * from`lv' although the reverse is true:
752 :     * if `lvc' is undertaken, `lv's count should
753 :     * *not* be updated!
754 :     * Luckily, `lvc' will not become dead while
755 :     * rebound to Con(lv) because it's used by the
756 :     * SWITCH. All in all, it works fine, but it's
757 :     * not as straightforward as it seems.
758 :     * - it seems to be a good idea, but it can hide
759 :     * other opt-opportunities since it hides the
760 :     * previous binding. *)
761 : monnier 189 val nm = addbind(nm, lvc, Con(lvc,slv,ndc,tycs))
762 : monnier 185 in (F.DATAcon(ndc, tycs, lv), loop nm le #2)
763 :     end
764 :     | carm (con,le) = (con, loop m le #2)
765 :     val narms = map carm arms
766 :     val ndef = Option.map (fn le => loop m le #2) def
767 :     in cont(m, F.SWITCH(sval2val sv, ac, narms, ndef))
768 :     end)
769 :    
770 : monnier 121 | sv as (Fun _ | TFun _) =>
771 :     bugval("unexpected switch arg", sval2val sv))
772 :    
773 : monnier 159 | F.CON (dc1,tycs1,v,lv,le) =>
774 : monnier 189 let val lvi = C.get lv
775 :     in if C.dead lvi then (click_deadval(); loop m le cont) else
776 : monnier 186 let val ndc = cdcon dc1
777 :     fun ccon sv =
778 : monnier 189 let val nm = addbind(m, lv, Con(lv, sv, ndc, tycs1))
779 : monnier 186 val nle = loop nm le cont
780 : monnier 189 in if C.dead lvi then nle
781 :     else F.CON(ndc, tycs1, sval2val sv, lv, nle)
782 : monnier 186 end
783 :     in case ((val2sval m v) handle x => raise x)
784 : monnier 189 of sv as (Decon (lvd,sv',dc2,tycs2)) =>
785 : monnier 186 if FU.dcon_eq(dc1, dc2) andalso tycs_eq(tycs1,tycs2) then
786 : monnier 189 (click_con();
787 :     loop (substitute(m, lv, sv', F.VAR lvd)) le cont)
788 : monnier 186 else ccon sv
789 :     | sv => ccon sv
790 :     end
791 : monnier 189 end
792 : monnier 121
793 :     | F.RECORD (rk,vs,lv,le) =>
794 : monnier 164 (* g: check whether the record already exists *)
795 : monnier 189 let val lvi = C.get lv
796 :     in if C.dead lvi then (click_deadval(); loop m le cont) else
797 :     let fun g (Select(_,sv,0)::ss) =
798 :     let fun g' (n,Select(_,sv',i)::ss) =
799 :     if n = i andalso (sval2val sv) = (sval2val sv')
800 :     then g'(n+1,ss) else NONE
801 :     | g' (n,[]) =
802 :     (case sval2lty sv
803 :     of SOME lty =>
804 :     let val ltd = case rk
805 :     of F.RK_STRUCT => LT.ltd_str
806 :     | F.RK_TUPLE _ => LT.ltd_tuple
807 :     | _ => buglexp("bogus rk",le)
808 :     in if length(ltd lty) = n
809 :     then SOME sv else NONE
810 :     end
811 :     | _ => (click_lacktype(); NONE)) (* sad *)
812 :     | g' _ = NONE
813 :     in g'(1,ss)
814 :     end
815 : monnier 186 | g _ = NONE
816 :     val svs = ((map (val2sval m) vs) handle x => raise x)
817 : monnier 189 in case g svs
818 :     of SOME sv => (click_record();
819 :     loop (substitute(m, lv, sv, F.INT 0)) le cont
820 :     before app (unuseval m) vs)
821 :     | _ =>
822 :     let val nm = addbind(m, lv, Record(lv, svs))
823 : monnier 186 val nle = loop nm le cont
824 : monnier 189 in if C.dead lvi then nle
825 :     else F.RECORD(rk, map sval2val svs, lv, nle)
826 : monnier 186 end
827 :     end
828 : monnier 189 end
829 : monnier 121
830 :     | F.SELECT (v,i,lv,le) =>
831 : monnier 189 let val lvi = C.get lv
832 :     in if C.dead lvi then (click_deadval(); loop m le cont) else
833 : monnier 186 (case ((val2sval m v) handle x => raise x)
834 : monnier 189 of Record (lvr,svs) =>
835 :     let val sv = List.nth(svs, i)
836 :     in click_select();
837 :     loop (substitute(m, lv, sv, F.VAR lvr)) le cont
838 : monnier 186 end
839 :     | sv =>
840 : monnier 189 let val nm = addbind (m, lv, Select(lv, sv, i))
841 : monnier 186 val nle = loop nm le cont
842 : monnier 189 in if C.dead lvi then nle
843 :     else F.SELECT(sval2val sv, i, lv, nle)
844 : monnier 186 end)
845 : monnier 189 end
846 : monnier 121
847 : monnier 184 | F.RAISE (v,ltys) =>
848 :     cont(m, F.RAISE((substval v) handle x => raise x, ltys))
849 : monnier 121
850 : monnier 184 | F.HANDLE (le,v) =>
851 :     cont(m, F.HANDLE(loop m le #2, (substval v) handle x => raise x))
852 : monnier 121
853 :     | F.BRANCH (po,vs,le1,le2) =>
854 :     let val nvs = ((map substval vs) handle x => raise x)
855 :     val npo = cpo po
856 : monnier 184 val nle1 = loop m le1 #2
857 :     val nle2 = loop m le2 #2
858 :     in cont(m, F.BRANCH(npo, nvs, nle1, nle2))
859 : monnier 121 end
860 :    
861 :     | F.PRIMOP (po,vs,lv,le) =>
862 : monnier 189 let val lvi = C.get lv
863 :     val pure = not(impurePO po)
864 :     in if pure andalso C.dead lvi then (click_deadval();loop m le cont) else
865 : monnier 186 let val nvs = ((map substval vs) handle x => raise x)
866 :     val npo = cpo po
867 :     val nm = addbind(m, lv, Var(lv,NONE))
868 :     val nle = loop nm le cont
869 :     in
870 : monnier 189 if pure andalso C.dead lvi then nle
871 :     else F.PRIMOP(npo, nvs, lv, nle)
872 : monnier 186 end
873 : monnier 121 end
874 :     end
875 :    
876 : monnier 185 in
877 :     (* C.collect fdec; *)
878 :     case cexp (DI.top,DI.top) S.empty
879 :     M.empty (F.FIX([fdec], F.RET[F.VAR f])) #2
880 :     of F.FIX([fdec], F.RET[F.VAR f]) => fdec
881 :     | fdec => bug "invalid return fundec"
882 :     end
883 : monnier 121
884 :     end
885 :     end

root@smlnj-gforge.cs.uchicago.edu
ViewVC Help
Powered by ViewVC 1.0.0