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 201 - (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 : monnier 159 *)
27 :    
28 : monnier 121 (* things that lcontract.sml does that fcontract doesn't do (yet):
29 : monnier 159 * - inline across DeBruijn depths (will be solved by named-tvar)
30 : monnier 121 * - elimination of let [dead-vs] = pure in body
31 :     *)
32 :    
33 :     (* things that cpsopt/eta.sml did that fcontract doesn't do:
34 : monnier 159 * - let f vs = select(v,i,g,g vs)
35 : monnier 121 *)
36 :    
37 :     (* things that cpsopt/contract.sml did that fcontract doesn't do:
38 : monnier 159 * - IF-idiom (I still don't know what it is)
39 : monnier 121 * - unifying branches
40 :     * - Handler operations
41 :     * - primops expressions
42 :     * - branch expressions
43 :     *)
44 :    
45 :     (* things that could also be added:
46 : monnier 184 * - elimination of dead vars in let
47 : monnier 191 * - elimination of constant arguments
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 200 structure LK = LtyKernel
189 : monnier 163 structure OU = OptUtils
190 : monnier 159 structure CTRL = Control.FLINT
191 : monnier 121 in
192 :    
193 :     val say = Control.Print.say
194 :     fun bug msg = ErrorMsg.impossible ("FContract: "^msg)
195 :     fun buglexp (msg,le) = (say "\n"; PP.printLexp le; bug msg)
196 :     fun bugval (msg,v) = (say "\n"; PP.printSval v; bug msg)
197 :    
198 :     (* fun sayexn e = app say (map (fn s => s^" <- ") (SMLofNJ.exnHistory e)) *)
199 :    
200 : monnier 159 val cplv = LambdaVar.dupLvar
201 : monnier 200 val mklv = LambdaVar.mkLvar
202 : monnier 121
203 :     datatype sval
204 :     = Val of F.value (* F.value should never be F.VAR lv *)
205 : monnier 197 | Fun of F.lvar * F.lexp * (F.lvar * F.lty) list * F.fkind
206 :     | TFun of F.lvar * F.lexp * (F.tvar * F.tkind) list
207 : monnier 189 | Record of F.lvar * sval list
208 :     | Con of F.lvar * sval * F.dcon * F.tyc list
209 :     | Decon of F.lvar * sval * F.dcon * F.tyc list
210 :     | Select of F.lvar * sval * int
211 : monnier 121 | Var of F.lvar * F.lty option (* cop out case *)
212 :    
213 : monnier 159 fun sval2lty (Var(_,x)) = x
214 :     | sval2lty (Decon(_,_,(_,_,lty),tycs)) =
215 :     SOME(hd(#2 (LT.ltd_arrow (hd(LT.lt_inst(lty, tycs))))))
216 : monnier 199 | sval2lty (Select(_,sv,i)) =
217 :     (case sval2lty sv of SOME lty => SOME(LT.lt_select(lty, i)) | _ => NONE)
218 : monnier 159 | sval2lty _ = NONE
219 : monnier 121
220 : monnier 159 fun tycs_eq ([],[]) = true
221 :     | tycs_eq (tyc1::tycs1,tyc2::tycs2) =
222 :     LT.tc_eqv(tyc1,tyc2) andalso tycs_eq(tycs1,tycs2)
223 :     | tycs_eq _ = false
224 : monnier 121
225 : monnier 200 (* calls `code' to append a lexp to each leaf of `le'.
226 :     * Typically used to transform `let lvs = le in code' so that
227 :     * `code' is now copied at the end of each branch of `le'.
228 :     * `lvs' is a list of lvars that should be used if the result of `le'
229 :     * needs to be bound before calling `code'. *)
230 :     fun append lvs code le =
231 :     let fun l (F.RET vs) = code vs
232 :     | l (le as (F.APP _ | F.TAPP _ | F.RAISE _ | F.HANDLE _)) =
233 :     let val lvs = map (fn lv => let val nlv = cplv lv
234 :     in C.new NONE nlv; nlv end)
235 :     lvs
236 :     in F.LET(lvs, le, code(map F.VAR lvs))
237 :     end
238 :     | l (F.LET (lvs,body,le)) = F.LET(lvs,body, l le)
239 :     | l (F.FIX (fdecs,le)) = F.FIX(fdecs, l le)
240 :     | l (F.TFN (tfdec,le)) = F.TFN(tfdec, l le)
241 :     | l (F.SWITCH (v,ac,arms,def)) =
242 :     let fun larm (con,le) = (con, l le)
243 :     in F.SWITCH(v, ac, map larm arms, O.map l def)
244 :     end
245 :     | l (F.CON (dc,tycs,v,lv,le)) = F.CON(dc, tycs, v, lv, l le)
246 :     | l (F.RECORD (rk,vs,lv,le)) = F.RECORD(rk, vs, lv, l le)
247 :     | l (F.SELECT (v,i,lv,le)) = F.SELECT(v, i, lv, l le)
248 :     | l (F.BRANCH (po,vs,le1,le2)) = F.BRANCH(po, vs, l le1, l le2)
249 :     | l (F.PRIMOP (po,vs,lv,le)) = F.PRIMOP(po, vs, lv, l le)
250 :     in l le
251 :     end
252 :    
253 : monnier 201 (* `extract' extracts the code of a switch arm into a function
254 :     * and replaces it with a call to that function *)
255 :     fun extract (con,le) =
256 :     let val f = mklv()
257 :     val fk = {isrec=NONE,known=true,inline=F.IH_SAFE,
258 :     cconv=F.CC_FUN(LK.FF_FIXED)}
259 :     in case con of
260 :     F.DATAcon(dc as (_,_,lty),tycs,lv) =>
261 :     let val nlv = cplv lv
262 :     val _ = C.new (SOME[lv]) f
263 :     val _ = C.use NONE (C.new NONE nlv)
264 :     val (lty,_) = LT.ltd_parrow(hd(LT.lt_inst(lty, tycs)))
265 :     in ((F.DATAcon(dc, tycs, nlv),
266 :     F.APP(F.VAR f, [F.VAR nlv])),
267 :     (fk, f, [(lv, lty)], le))
268 :     end
269 :     | con =>
270 :     let val _ = C.new (SOME[]) f
271 :     in ((con, F.APP(F.VAR f, [])),
272 :     (fk, f, [], le))
273 :     end
274 :     end
275 :    
276 : monnier 189 fun click s c = (if !CTRL.misc = 1 then say s else (); Stats.addCounter c 1)
277 : monnier 185
278 : monnier 189 (* val c_inline = Stats.newCounter[] *)
279 :     (* val c_deadval = Stats.newCounter[] *)
280 :     (* val c_deadlexp = Stats.newCounter[] *)
281 :     (* val c_select = Stats.newCounter[] *)
282 :     (* val c_record = Stats.newCounter[] *)
283 :     (* val c_lacktype = Stats.newCounter[] *)
284 :     (* val c_con = Stats.newCounter[] *)
285 :     (* val c_switch = Stats.newCounter[] *)
286 :     (* val c_eta = Stats.newCounter[] *)
287 :     (* val c_etasplit = Stats.newCounter[] *)
288 :     (* val c_branch = Stats.newCounter[] *)
289 :     (* val c_dropargs = Stats.newCounter[] *)
290 : monnier 185
291 : monnier 189 fun contract (fdec as (_,f,_,_), counter) = let
292 :    
293 :     val c_dummy = Stats.newCounter[]
294 :     val c_miss = Stats.newCounter[]
295 :    
296 :     fun click_deadval () = (click "d" counter)
297 :     fun click_deadlexp () = (click "D" counter)
298 :     fun click_select () = (click "s" counter)
299 :     fun click_record () = (click "r" counter)
300 :     fun click_con () = (click "c" counter)
301 :     fun click_switch () = (click "s" counter)
302 :     fun click_eta () = (click "e" counter)
303 :     fun click_etasplit () = (click "E" counter)
304 :     fun click_branch () = (click "b" counter)
305 :     fun click_dropargs () = (click "a" counter)
306 :    
307 :     fun click_lacktype () = (click "t" c_miss)
308 :    
309 :     (* this counters is actually *used* by fcontract.
310 :     * It's not used just for statistics. *)
311 :     val c_inline = Stats.newCounter[counter]
312 :     (* val c_inline1 = Stats.newCounter[c_inline] *)
313 :     (* val c_inline2 = Stats.newCounter[c_inline] *)
314 :     (* val c_unroll = Stats.newCounter[c_inline] *)
315 :     fun click_simpleinline () = (click "i" c_inline)
316 :     fun click_copyinline () = (click "I" c_inline)
317 :     fun click_unroll () = (click "u" c_inline)
318 :     fun inline_count () = Stats.getCounter c_inline
319 :    
320 : monnier 186 fun used lv = (C.usenb(C.get lv) > 0)
321 : monnier 199 (* handle x =>
322 : monnier 186 (say("while in FContract.used "^(C.LVarString lv)^"\n");
323 : monnier 199 raise x) *)
324 : monnier 121
325 :     fun impurePO po = true (* if a PrimOP is pure or not *)
326 :    
327 :     fun eqConV (F.INTcon i1, F.INT i2) = i1 = i2
328 :     | eqConV (F.INT32con i1, F.INT32 i2) = i1 = i2
329 :     | eqConV (F.WORDcon i1, F.WORD i2) = i1 = i2
330 :     | eqConV (F.WORD32con i1, F.WORD32 i2) = i1 = i2
331 :     | eqConV (F.REALcon r1, F.REAL r2) = r1 = r2
332 :     | eqConV (F.STRINGcon s1, F.STRING s2) = s1 = s2
333 :     | eqConV (con,v) = bugval("unexpected comparison with val", v)
334 :    
335 :     fun lookup m lv = (M.lookup m lv)
336 :     (* handle e as M.IntmapF =>
337 :     (say "\nlooking up unbound ";
338 :     say (!PP.LVarString lv);
339 :     raise e) *)
340 :    
341 :     fun sval2val sv =
342 :     case sv
343 : monnier 159 of (Fun{1=lv,...} | TFun{1=lv,...} | Record{1=lv,...} | Decon{1=lv,...}
344 : monnier 121 | Con{1=lv,...} | Select{1=lv,...} | Var{1=lv,...}) => F.VAR lv
345 :     | Val v => v
346 :    
347 : monnier 163 fun val2sval m (F.VAR ov) =
348 : monnier 199 ((lookup m ov) (* handle x =>
349 :     (say("val2sval "^(C.LVarString ov)^"\n"); raise x) *) )
350 : monnier 121 | val2sval m v = Val v
351 :    
352 :     fun bugsv (msg,sv) = bugval(msg, sval2val sv)
353 :    
354 :     fun subst m ov = sval2val (lookup m ov)
355 : monnier 199 fun substval m = sval2val o (val2sval m)
356 :     fun substvar m lv =
357 :     case substval m (F.VAR lv)
358 : monnier 121 of F.VAR lv => lv
359 :     | v => bugval ("unexpected val", v)
360 :    
361 :     (* called when a variable becomes dead.
362 :     * it simply adjusts the use-counts *)
363 :     fun undertake m lv =
364 :     let val undertake = undertake m
365 :     in case lookup m lv
366 : monnier 186 of Var {1=nlv,...} => ()
367 : monnier 121 | Val v => ()
368 : monnier 197 | Fun (lv,le,args,_) =>
369 : monnier 187 C.unuselexp undertake
370 :     (F.LET(map #1 args,
371 :     F.RET (map (fn _ => F.INT 0) args),
372 :     le))
373 :     | TFun{1=lv,2=le,...} =>
374 :     C.unuselexp undertake le
375 : monnier 189 | (Select {2=sv,...} | Con {2=sv,...}) => unusesval m sv
376 :     | Record {2=svs,...} => app (unusesval m) svs
377 : monnier 159 (* decon's are implicit so we can't get rid of them *)
378 :     | Decon _ => ()
379 : monnier 121 end
380 :     handle M.IntmapF =>
381 : monnier 186 (say("Unable to undertake "^(C.LVarString lv)^"\n"))
382 : monnier 121 | x =>
383 : monnier 186 (say("while undertaking "^(C.LVarString lv)^"\n"); raise x)
384 : monnier 121
385 : monnier 189 and unusesval m sv = unuseval m (sval2val sv)
386 : monnier 187 and unuseval m (F.VAR lv) =
387 :     if (C.unuse false (C.get lv)) then undertake m lv else ()
388 :     | unuseval f _ = ()
389 :     fun unusecall m lv =
390 :     if (C.unuse true (C.get lv)) then undertake m lv else ()
391 :    
392 :    
393 : monnier 121 fun addbind (m,lv,sv) = M.add(m, lv, sv)
394 :    
395 : monnier 164 (* substitute a value sv for a variable lv and unuse value v. *)
396 : monnier 121 fun substitute (m, lv1, sv, v) =
397 :     (case sval2val sv of F.VAR lv2 => C.transfer(lv1,lv2) | v2 => ();
398 : monnier 187 unuseval m v;
399 : monnier 199 addbind(m, lv1, sv)) (* handle x =>
400 : monnier 186 (say ("while substituting "^
401 : monnier 164 (C.LVarString lv1)^
402 :     " -> ");
403 : monnier 121 PP.printSval (sval2val sv);
404 : monnier 199 raise x) *)
405 : monnier 121
406 :     (* common code for primops *)
407 : monnier 199 fun cpo m (SOME{default,table},po,lty,tycs) =
408 :     (SOME{default=substvar m default,
409 :     table=map (fn (tycs,lv) => (tycs, substvar m lv)) table},
410 : monnier 121 po,lty,tycs)
411 : monnier 199 | cpo _ po = po
412 : monnier 121
413 : monnier 199 fun cdcon m (s,Access.EXN(Access.LVAR lv),lty) =
414 :     (s, Access.EXN(Access.LVAR(substvar m lv)), lty)
415 :     | cdcon _ dc = dc
416 : monnier 121
417 : monnier 201 (* ifs (inlined functions): records which functions we're currently inlining
418 : monnier 199 * in order to detect loops
419 :     * m: is a map lvars to their defining expressions (svals) *)
420 : monnier 201 fun fcexp ifs m le cont = let
421 :     val loop = fcexp ifs
422 : monnier 199 val substval = substval m
423 :     val cdcon = cdcon m
424 :     val cpo = cpo m
425 : monnier 163
426 : monnier 201 fun fcLet (lvs,le,body) =
427 :     loop m le
428 :     (fn (nm,nle) =>
429 :     let fun cbody () =
430 :     let val nm = (foldl (fn (lv,m) =>
431 :     addbind(m, lv, Var(lv, NONE)))
432 :     nm lvs)
433 :     in case loop nm body cont
434 :     of F.RET vs => if vs = (map F.VAR lvs) then nle
435 :     else F.LET(lvs, nle, F.RET vs)
436 :     | nbody => F.LET(lvs, nle, nbody)
437 :     end
438 :     in case nle
439 :     of F.RET vs =>
440 :     let fun simplesubst (lv,v,m) =
441 :     let val sv = val2sval m v
442 :     in substitute(m, lv, sv, sval2val sv)
443 :     end
444 :     val nm = (ListPair.foldl simplesubst nm (lvs, vs))
445 :     in loop nm body cont
446 :     end
447 :     | F.TAPP _ =>
448 :     if List.all (C.dead o C.get) lvs
449 :     then loop nm body cont
450 :     else cbody()
451 :     | (F.BRANCH _ | F.SWITCH _) =>
452 :     (* this is a hack originally meant to cleanup the BRANCH
453 :     * mess introduced in flintnm (where each branch returns
454 :     * just true or false which is generally only used as
455 :     * input to a SWITCH).
456 :     * The present code does more than clean up this case.
457 :     * It has one serious shortcoming: it ends up making
458 :     * three fcontract passes through the same code (plus
459 :     * one cheap traversal). *)
460 :     let fun cassoc (lv,F.SWITCH(F.VAR v,ac,arms,NONE),wrap) =
461 :     if lv <> v orelse C.usenb(C.get lv) > 1
462 :     then cbody() else
463 :     let val (narms,fdecs) =
464 :     ListPair.unzip (map extract arms)
465 :     fun addswitch [v] =
466 :     C.copylexp
467 :     IntmapF.empty
468 :     (F.SWITCH(v,ac,narms,NONE))
469 :     | addswitch _ = bug "prob in addswitch"
470 :     (* replace each leaf `ret' with a copy
471 :     * of the switch *)
472 :     val nle = append [lv] addswitch nle
473 :     (* decorate with the functions extracted
474 :     * from the switch arms *)
475 :     val nle =
476 :     foldl (fn (f,le) => F.FIX([f],le))
477 :     (wrap nle) fdecs
478 :     (* Ugly hack: force one more traversal *)
479 :     val nle = loop nm nle #2
480 :     in click_branch();
481 :     loop nm nle cont
482 :     end
483 :     | cassoc _ = cbody()
484 :     in case (lvs,body)
485 :     of ([lv],le as F.SWITCH _) =>
486 :     cassoc(lv, le, fn x => x)
487 :     | ([lv],F.LET(lvs,le as F.SWITCH _,rest)) =>
488 :     cassoc(lv, le, fn le => F.LET(lvs,le,rest))
489 :     | _ => cbody()
490 :     end
491 :     | _ => cbody()
492 :     end)
493 : monnier 200
494 : monnier 201 fun fcFix (fs,le) =
495 :     let (* The actual function contraction *)
496 :     fun fcFun (m,[]:F.fundec list,acc) = acc
497 :     | fcFun (m,fdec as ({inline,cconv,known,isrec},f,args,body)::fs,acc) =
498 :     let val fi = C.get f
499 :     in if C.dead fi then fcFun(m, fs, acc)
500 :     else if C.iusenb fi = C.usenb fi then
501 :     (* we need to be careful that undertake not be called
502 :     * recursively *)
503 :     (C.use NONE fi; undertake m f; fcFun(m, fs, acc))
504 :     else
505 :     let (* val _ = say ("\nEntering "^(C.LVarString f)) *)
506 :     val saved_ic = inline_count()
507 :     (* make up the bindings for args inside the body *)
508 :     fun addnobind ((lv,lty),m) =
509 :     addbind(m, lv, Var(lv, SOME lty))
510 :     val nm = foldl addnobind m args
511 :     (* contract the body and create the resulting fundec *)
512 :     val nbody = fcexp (S.add(f, ifs)) nm body #2
513 :     (* if inlining took place, the body might be completely
514 :     * changed (read: bigger), so we have to reset the
515 :     * `inline' bit *)
516 :     val nfk = {isrec=isrec, cconv=cconv,
517 :     known=known orelse not(C.escaping fi),
518 :     inline=if inline_count() = saved_ic
519 :     then inline
520 :     else F.IH_SAFE}
521 :     (* update the binding in the map. This step is
522 :     * not just a mere optimization but is necessary
523 :     * because if we don't do it and the function
524 :     * gets inlined afterwards, the counts will reflect the
525 :     * new contracted code while we'll be working on the
526 :     * the old uncontracted code *)
527 :     val nm = addbind(m, f, Fun(f, nbody, args, nfk))
528 :     in fcFun(nm, fs, (nfk, f, args, nbody)::acc)
529 :     (* before say ("\nExiting "^(C.LVarString f)) *)
530 :     end
531 :     end
532 :    
533 :     (* check for eta redex *)
534 :     fun fcEta (fdec as (fk,f,args,F.APP(F.VAR g,vs)):F.fundec,
535 :     (m,fs,hs)) =
536 :     if List.length args = List.length vs andalso
537 :     OU.ListPair_all (fn (v,(lv,t)) =>
538 :     case v of F.VAR v => v = lv andalso lv <> g
539 :     | _ => false)
540 :     (vs, args)
541 :     then
542 :     let val svg = lookup m g
543 :     val g = case sval2val svg
544 :     of F.VAR g => g
545 :     | v => bugval("not a variable", v)
546 :     (* NOTE: we don't want to turn a known function into an
547 :     * escaping one. It's dangerous for optimisations based
548 :     * on known functions (elimination of dead args, f.ex)
549 :     * and could generate cases where call>use in collect *)
550 :     in if (C.escaping(C.get f)) andalso not(C.escaping(C.get g))
551 :     (* the default case could ensure the inline *)
552 :     then (m, fdec::fs, hs)
553 :     else let
554 :     (* if an earlier function h has been eta-reduced
555 :     * to f, we have to be careful to update its
556 :     * binding to not refer to f any more since f
557 :     * will disappear *)
558 :     val nm = foldl (fn (h,m) =>
559 :     if sval2val(lookup m h) = F.VAR f
560 :     then addbind(m, h, svg) else m)
561 :     m hs
562 :     in
563 :     (* I could almost reuse `substitute' but the
564 :     * unuse in substitute assumes the val is escaping *)
565 :     click_eta();
566 :     C.transfer(f, g);
567 :     unusecall m g;
568 :     (addbind(m, f, svg), fs, f::hs)
569 :     end
570 : monnier 189 end
571 : monnier 201 else (m, fdec::fs, hs)
572 :     | fcEta (fdec,(m,fs,hs)) = (m,fdec::fs,hs)
573 :    
574 :     (* add wrapper for various purposes *)
575 :     fun wrap (f as ({inline=F.IH_ALWAYS,...},_,_,_):F.fundec,fs) = f::fs
576 :     | wrap (f as (fk as {isrec,...},g,args,body):F.fundec,fs) =
577 :     let val gi = C.get g
578 :     fun dropargs filter =
579 :     let val (nfk,nfk') = OU.fk_wrap(fk, O.map #1 isrec)
580 :     val args' = filter args
581 :     val ng = cplv g
582 :     val nargs = map (fn (v,t) => (cplv v, t)) args
583 :     val nargs' = map #1 (filter nargs)
584 :     val appargs = (map F.VAR nargs')
585 :     val nf = (nfk, g, nargs, F.APP(F.VAR ng, appargs))
586 :     val nf' = (nfk', ng, args', body)
587 :    
588 :     val ngi = C.new (SOME(map #1 args')) ng
589 :     in
590 :     C.ireset gi;
591 :     app (ignore o (C.new NONE) o #1) nargs;
592 :     C.use (SOME appargs) ngi;
593 :     app (C.use NONE o C.get) nargs';
594 :     nf'::nf::fs
595 : monnier 121 end
596 : monnier 201 in
597 :     (* Don't introduce wrappers for escaping-only functions.
598 :     * This is debatable since although wrappers are useless
599 :     * on escaping-only functions, some of the escaping uses
600 :     * might turn into calls in the course of fcontract, so
601 :     * by not introducing wrappers here, we avoid useless work
602 :     * but we also postpone useful work to later invocations. *)
603 :     if C.dead gi then fs else
604 :     let val used = map (used o #1) args
605 :     in if C.called gi then
606 :     (* if some args are not used, let's drop them *)
607 :     if not (List.all (fn x => x) used) then
608 :     (click_dropargs();
609 :     dropargs (fn xs => OU.filter(used, xs)))
610 : monnier 190
611 : monnier 201 (* eta-split: add a wrapper for escaping uses *)
612 :     else if C.escaping gi then
613 :     (* like dropargs but keeping all args *)
614 :     (click_etasplit(); dropargs (fn x => x))
615 :    
616 :     else f::fs
617 :     else f::fs
618 :     end
619 :     end
620 :    
621 :     (* add various wrappers *)
622 :     val fs = foldl wrap [] fs
623 :    
624 :     (* register the new bindings (uncontracted for now) *)
625 :     val nm = foldl (fn (fdec as (fk,f,args,body),m) =>
626 :     addbind(m, f, Fun(f, body, args, fk)))
627 :     m fs
628 :     (* check for eta redexes *)
629 :     val (nm,fs,_) = foldl fcEta (nm,[],[]) fs
630 :    
631 :     (* move the inlinable functions to the end of the list *)
632 :     val (f1s,f2s) =
633 :     List.partition (fn ({inline=F.IH_ALWAYS,...},_,_,_) => true
634 :     | _ => false) fs
635 :     val fs = f2s @ f1s
636 :    
637 :     (* contract the main body *)
638 :     val nle = loop nm le cont
639 :     (* contract the functions *)
640 :     val fs = fcFun(nm, fs, [])
641 :     (* junk newly unused funs *)
642 :     val fs = List.filter (used o #2) fs
643 :     in
644 :     case fs
645 :     of [] => nle
646 :     | [f1 as ({isrec=NONE,...},_,_,_),f2] =>
647 :     (* gross hack: `wrap' might have added a second
648 :     * non-recursive function. we need to split them into
649 :     * 2 FIXes. This is _very_ ad-hoc *)
650 :     F.FIX([f2], F.FIX([f1], nle))
651 :     | _ => F.FIX(fs, nle)
652 :     end
653 : monnier 163
654 : monnier 201 fun fcApp (f,vs) =
655 :     let val nvs = map substval vs
656 :     val svf = val2sval m f
657 :     (* F.APP inlining (if any) *)
658 :     in case svf
659 :     of Fun(g,body,args,{inline,...}) =>
660 :     if (C.usenb(C.get g)) = 1 andalso not(S.member ifs g) then
661 :    
662 :     (* simple inlining: we should copy the body and then
663 :     * kill the function, but instead we just move the body
664 :     * and kill only the function name.
665 :     * This inlining strategy looks inoffensive enough,
666 :     * but still requires some care: see comments at the
667 :     * begining of this file and in cfun *)
668 :     (click_simpleinline();
669 :     ignore(C.unuse true (C.get g));
670 :     loop m (F.LET(map #1 args, F.RET vs, body)) cont)
671 :    
672 :     (* aggressive inlining. We allow pretty much
673 :     * any inlinling, but we detect and reject inlining
674 :     * recursively which would else lead to infinite loop *)
675 :     (* unrolling is not as straightforward as it seems:
676 :     * if you inline the function you're currently
677 :     * fcontracting, you're asking for trouble: there is a
678 :     * hidden assumption in the counting that the old code
679 :     * will be replaced by the new code (and is hence dead).
680 :     * If the function to be unrolled has the only call to
681 :     * function f, then f might get simpleinlined before
682 :     * unrolling, which means that unrolling will introduce
683 :     * a second occurence of the `only call' but at that point
684 :     * f has already been killed. *)
685 :     else if (inline = F.IH_ALWAYS andalso not(S.member ifs g)) then
686 :     let val nle =
687 :     C.copylexp M.empty (F.LET(map #1 args, F.RET vs, body))
688 :     in
689 :     click_copyinline();
690 :     (app (unuseval m) vs);
691 :     unusecall m g;
692 :     fcexp (S.add(g, ifs)) m nle cont
693 :     end
694 :     else cont(m,F.APP(sval2val svf, nvs))
695 :     | sv => cont(m,F.APP(sval2val svf, nvs))
696 :     end
697 : monnier 184
698 : monnier 201 fun fcTfn ((f,args,body),le) =
699 :     let val fi = C.get f
700 :     in if C.dead fi then (click_deadlexp(); loop m le cont) else
701 :     let val nbody = fcexp ifs m body #2
702 :     val nm = addbind(m, f, TFun(f, nbody, args))
703 : monnier 184 val nle = loop nm le cont
704 : monnier 121 in
705 : monnier 201 if C.dead fi then nle else F.TFN((f, args, nbody), nle)
706 : monnier 121 end
707 : monnier 201 end
708 :    
709 :     fun fcSwitch (v,ac,arms,def) =
710 :     let fun fcsCon (lvc,svc,dc1:F.dcon,tycs1) =
711 :     let fun killle le = C.unuselexp (undertake m) le
712 :     fun kill lv le =
713 :     C.unuselexp (undertake (addbind(m,lv,Var(lv,NONE)))) le
714 :     fun killarm (F.DATAcon(_,_,lv),le) = kill lv le
715 :     | killarm _ = buglexp("bad arm in switch(con)", le)
716 :    
717 :     fun carm ((F.DATAcon(dc2,tycs2,lv),le)::tl) =
718 :     (* sometimes lty1 <> lty2 :-( so this doesn't work:
719 :     * FU.dcon_eq(dc1, dc2) andalso tycs_eq(tycs1,tycs2) *)
720 :     if #2 dc1 = #2 (cdcon dc2) then
721 :     (map killarm tl; (* kill the rest *)
722 :     O.map killle def; (* and the default case *)
723 :     loop (substitute(m, lv, svc, F.VAR lvc))
724 :     le cont)
725 :     else
726 :     (* kill this arm and continue with the rest *)
727 :     (kill lv le; carm tl)
728 :     | carm [] = loop m (O.valOf def) cont
729 :     | carm _ = buglexp("unexpected arm in switch(con,...)", le)
730 :     in click_switch(); carm arms
731 : monnier 186 end
732 : monnier 121
733 : monnier 201 fun fcsVal v =
734 :     let fun kill le = C.unuselexp (undertake m) le
735 :     fun carm ((con,le)::tl) =
736 :     if eqConV(con, v) then
737 :     (map (kill o #2) tl;
738 :     O.map kill def;
739 :     loop m le cont)
740 :     else (kill le; carm tl)
741 :     | carm [] = loop m (O.valOf def) cont
742 :     in click_switch(); carm arms
743 :     end
744 :    
745 :     fun fcsDefault (sv,lvc) =
746 :     case (arms,def)
747 :     of ([(F.DATAcon(dc,tycs,lv),le)],NONE) =>
748 :     (* this is a mere DECON, so we can push the let binding
749 :     * (hidden in cont) inside and maybe even drop the DECON *)
750 :     let val ndc = cdcon dc
751 :     val slv = Decon(lv, sv, ndc, tycs)
752 :     val nm = addbind(m, lv, slv)
753 :     (* see below *)
754 :     (* val nm = addbind(nm, lvc, Con(lvc, slv, ndc, tycs)) *)
755 :     val nle = loop nm le cont
756 :     val nv = sval2val sv
757 :     in
758 :     if used lv then
759 :     F.SWITCH(nv,ac,[(F.DATAcon(ndc,tycs,lv),nle)],NONE)
760 :     else (unuseval m nv; nle)
761 :     end
762 :     | (([(_,le)],NONE) | ([],SOME le)) =>
763 :     (* This should never happen, but we can optimize it away *)
764 :     (unuseval m (sval2val sv); loop m le cont)
765 :     | _ =>
766 :     let fun carm (F.DATAcon(dc,tycs,lv),le) =
767 :     let val ndc = cdcon dc
768 :     val slv = Decon(lv, sv, ndc, tycs)
769 :     val nm = addbind(m, lv, slv)
770 :     (* we can rebind lv to a more precise value
771 :     * !!BEWARE!! This rebinding is misleading:
772 :     * - it gives the impression that `lvc' is built
773 :     * from`lv' although the reverse is true:
774 :     * if `lvc' is undertaken, `lv's count should
775 :     * *not* be updated!
776 :     * Luckily, `lvc' will not become dead while
777 :     * rebound to Con(lv) because it's used by the
778 :     * SWITCH. All in all, it works fine, but it's
779 :     * not as straightforward as it seems.
780 :     * - it seems to be a good idea, but it can hide
781 :     * other opt-opportunities since it hides the
782 :     * previous binding. *)
783 :     (* val nm = addbind(nm, lvc, Con(lvc,slv,ndc,tycs)) *)
784 :     in (F.DATAcon(ndc, tycs, lv), loop nm le #2)
785 :     end
786 :     | carm (con,le) = (con, loop m le #2)
787 :     val narms = map carm arms
788 :     val ndef = Option.map (fn le => loop m le #2) def
789 :     in cont(m, F.SWITCH(sval2val sv, ac, narms, ndef))
790 :     end
791 : monnier 121
792 : monnier 201 in case val2sval m v
793 :     of sv as Con x => fcsCon x
794 :     | sv as Val v => fcsVal v
795 :     | sv as (Var{1=lvc,...} | Select{1=lvc,...} | Decon{1=lvc, ...}
796 :     | (* will probably never happen *) Record{1=lvc,...}) =>
797 :     fcsDefault(sv, lvc)
798 :     | sv as (Fun _ | TFun _) =>
799 :     bugval("unexpected switch arg", sval2val sv)
800 :     end
801 : monnier 159
802 : monnier 201 fun fcCon (dc1,tycs1,v,lv,le) =
803 :     let val lvi = C.get lv
804 :     in if C.dead lvi then (click_deadval(); loop m le cont) else
805 :     let val ndc = cdcon dc1
806 :     fun ccon sv =
807 :     let val nm = addbind(m, lv, Con(lv, sv, ndc, tycs1))
808 :     val nle = loop nm le cont
809 :     in if C.dead lvi then nle
810 :     else F.CON(ndc, tycs1, sval2val sv, lv, nle)
811 :     end
812 :     in case val2sval m v
813 :     of sv as (Decon (lvd,sv',dc2,tycs2)) =>
814 :     if FU.dcon_eq(dc1, dc2) andalso tycs_eq(tycs1,tycs2) then
815 :     (click_con();
816 :     loop (substitute(m, lv, sv', F.VAR lvd)) le cont)
817 :     else ccon sv
818 :     | sv => ccon sv
819 : monnier 189 end
820 : monnier 201 end
821 : monnier 121
822 : monnier 201 fun fcRecord (rk,vs,lv,le) =
823 :     (* g: check whether the record already exists *)
824 :     let val lvi = C.get lv
825 :     in if C.dead lvi then (click_deadval(); loop m le cont) else
826 :     let fun g (Select(_,sv,0)::ss) =
827 :     let fun g' (n,Select(_,sv',i)::ss) =
828 :     if n = i andalso (sval2val sv) = (sval2val sv')
829 :     then g'(n+1,ss) else NONE
830 :     | g' (n,[]) =
831 :     (case sval2lty sv
832 :     of SOME lty =>
833 :     let val ltd = case rk
834 :     of F.RK_STRUCT => LT.ltd_str
835 :     | F.RK_TUPLE _ => LT.ltd_tuple
836 :     | _ => buglexp("bogus rk",le)
837 :     in if length(ltd lty) = n
838 :     then SOME sv else NONE
839 :     end
840 :     | _ => (click_lacktype(); NONE)) (* sad *)
841 :     | g' _ = NONE
842 :     in g'(1,ss)
843 :     end
844 :     | g _ = NONE
845 :     val svs = map (val2sval m) vs
846 :     in case g svs
847 :     of SOME sv => (click_record();
848 :     loop (substitute(m, lv, sv, F.INT 0)) le cont
849 :     before app (unuseval m) vs)
850 :     | _ =>
851 :     let val nm = addbind(m, lv, Record(lv, svs))
852 :     val nle = loop nm le cont
853 :     in if C.dead lvi then nle
854 :     else F.RECORD(rk, map sval2val svs, lv, nle)
855 :     end
856 : monnier 189 end
857 : monnier 201 end
858 : monnier 121
859 : monnier 201 fun fcSelect (v,i,lv,le) =
860 :     let val lvi = C.get lv
861 :     in if C.dead lvi then (click_deadval(); loop m le cont) else
862 :     (case val2sval m v
863 :     of Record (lvr,svs) =>
864 :     let val sv = List.nth(svs, i)
865 :     in click_select();
866 :     loop (substitute(m, lv, sv, F.VAR lvr)) le cont
867 :     end
868 :     | sv =>
869 :     let val nm = addbind (m, lv, Select(lv, sv, i))
870 :     val nle = loop nm le cont
871 :     in if C.dead lvi then nle
872 :     else F.SELECT(sval2val sv, i, lv, nle)
873 :     end)
874 :     end
875 : monnier 121
876 : monnier 201 fun fcBranch (po,vs,le1,le2) =
877 :     let val nvs = map substval vs
878 :     val npo = cpo po
879 :     val nle1 = loop m le1 #2
880 :     val nle2 = loop m le2 #2
881 :     in cont(m, F.BRANCH(npo, nvs, nle1, nle2))
882 :     end
883 : monnier 121
884 : monnier 201 fun fcPrimop (po,vs,lv,le) =
885 :     let val lvi = C.get lv
886 :     val pure = not(impurePO po)
887 :     in if pure andalso C.dead lvi then (click_deadval();loop m le cont) else
888 : monnier 199 let val nvs = map substval vs
889 : monnier 121 val npo = cpo po
890 : monnier 201 val nm = addbind(m, lv, Var(lv,NONE))
891 :     val nle = loop nm le cont
892 :     in
893 :     if pure andalso C.dead lvi then nle
894 :     else F.PRIMOP(npo, nvs, lv, nle)
895 : monnier 121 end
896 : monnier 201 end
897 : monnier 121
898 : monnier 201 in case le
899 :     of F.RET vs => cont(m, F.RET(map substval vs))
900 :     | F.LET x => fcLet x
901 :     | F.FIX x => fcFix x
902 :     | F.APP x => fcApp x
903 :     | F.TFN x => fcTfn x
904 :     | F.TAPP (f,tycs) => cont(m, F.TAPP(substval f, tycs))
905 :     | F.SWITCH x => fcSwitch x
906 :     | F.CON x => fcCon x
907 :     | F.RECORD x => fcRecord x
908 :     | F.SELECT x => fcSelect x
909 :     | F.RAISE (v,ltys) => cont(m, F.RAISE(substval v, ltys))
910 :     | F.HANDLE (le,v) => cont(m, F.HANDLE(loop m le #2, substval v))
911 :     | F.BRANCH x => fcBranch x
912 :     | F.PRIMOP x => fcPrimop x
913 : monnier 121 end
914 :    
915 : monnier 185 in
916 :     (* C.collect fdec; *)
917 : monnier 201 case fcexp S.empty
918 : monnier 185 M.empty (F.FIX([fdec], F.RET[F.VAR f])) #2
919 :     of F.FIX([fdec], F.RET[F.VAR f]) => fdec
920 :     | fdec => bug "invalid return fundec"
921 :     end
922 : monnier 121
923 :     end
924 :     end

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