[project @ 1998-12-02 13:17:09 by simonm]
[ghc-hetmet.git] / ghc / compiler / simplStg / LambdaLift.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1994-1998
3 %
4 \section[LambdaLift]{A STG-code lambda lifter}
5
6 \begin{code}
7 module LambdaLift ( liftProgram ) where
8
9 #include "HsVersions.h"
10
11 import StgSyn
12
13 import Bag              ( Bag, emptyBag, unionBags, unitBag, snocBag, bagToList )
14 import Id               ( mkSysLocal, idType, setIdArity, 
15                           setIdVisibility, Id
16                         )
17 import VarSet
18 import VarEnv
19 import IdInfo           ( exactArity )
20 import Name             ( Module )
21 import Type             ( splitForAllTys, mkForAllTys, mkFunTys, Type )
22 import UniqSupply       ( uniqFromSupply, splitUniqSupply, UniqSupply )
23 import Util             ( zipEqual, panic, assertPanic )
24 \end{code}
25
26 This is the lambda lifter.  It turns lambda abstractions into
27 supercombinators on a selective basis:
28
29 * Let-no-escaped bindings are never lifted. That's one major reason
30   why the lambda lifter is done in STG.
31
32 * Non-recursive bindings whose RHS is a lambda abstractions are lifted,
33   provided all the occurrences of the bound variable is in a function
34   postition.  In this example, f will be lifted:
35
36         let
37           f = \x -> e
38         in
39         ..(f a1)...(f a2)...
40   thus
41
42     $f p q r x = e      -- Supercombinator
43
44         ..($f p q r a1)...($f p q r a2)...
45
46   NOTE that the original binding is eliminated.
47
48   But in this case, f won't be lifted:
49
50         let
51           f = \x -> e
52         in
53         ..(g f)...(f a2)...
54
55   Why? Because we have to heap-allocate a closure for f thus:
56
57     $f p q r x = e      -- Supercombinator
58
59         let
60           f = $f p q r
61         in
62         ..(g f)...($f p q r a2)..
63
64   so it might as well be the original lambda abstraction.
65
66   We also do not lift if the function has an occurrence with no arguments, e.g.
67
68         let
69           f = \x -> e
70         in f
71
72   as this form is more efficient than if we create a partial application
73
74   $f p q r x = e      -- Supercombinator
75
76         f p q r
77
78 * Recursive bindings *all* of whose RHSs are lambda abstractions are
79   lifted iff
80         - all the occurrences of all the binders are in a function position
81         - there aren't ``too many'' free variables.
82
83   Same reasoning as before for the function-position stuff.  The ``too many
84   free variable'' part comes from considering the (potentially many)
85   recursive calls, which may now have lots of free vars.
86
87 Recent Observations:
88
89 * 2 might be already ``too many'' variables to abstract.
90   The problem is that the increase in the number of free variables
91   of closures refering to the lifted function (which is always # of
92   abstracted args - 1) may increase heap allocation a lot.
93   Expeiments are being done to check this...
94
95 * We do not lambda lift if the function has at least one occurrence
96   without any arguments. This caused lots of problems. Ex:
97   h = \ x -> ... let y = ...
98                  in let let f = \x -> ...y...
99                     in f
100   ==>
101   f = \y x -> ...y...
102   h = \ x -> ... let y = ...
103                  in f y
104
105   now f y is a partial application, so it will be updated, and this
106   is Bad.
107
108
109 --- NOT RELEVANT FOR STG ----
110 * All ``lone'' lambda abstractions are lifted.  Notably this means lambda
111   abstractions:
112         - in a case alternative: case e of True -> (\x->b)
113         - in the body of a let:  let x=e in (\y->b)
114 -----------------------------
115
116 %************************************************************************
117 %*                                                                      *
118 \subsection[Lift-expressions]{The main function: liftExpr}
119 %*                                                                      *
120 %************************************************************************
121
122 \begin{code}
123 liftProgram :: Module -> UniqSupply -> [StgBinding] -> [StgBinding]
124 liftProgram mod us prog = concat (runLM mod Nothing us (mapLM liftTopBind prog))
125
126
127 liftTopBind :: StgBinding -> LiftM [StgBinding]
128 liftTopBind (StgNonRec id rhs)
129   = dontLiftRhs rhs             `thenLM` \ (rhs', rhs_info) ->
130     returnLM (getScBinds rhs_info ++ [StgNonRec id rhs'])
131
132 liftTopBind (StgRec pairs)
133   = mapAndUnzipLM dontLiftRhs rhss      `thenLM` \ (rhss', rhs_infos) ->
134     returnLM ([co_rec_ify (StgRec (ids `zip` rhss') :
135                            getScBinds (unionLiftInfos rhs_infos))
136              ])
137   where
138    (ids, rhss) = unzip pairs
139 \end{code}
140
141
142 \begin{code}
143 liftExpr :: StgExpr
144          -> LiftM (StgExpr, LiftInfo)
145
146
147 liftExpr expr@(StgCon con args _) = returnLM (expr, emptyLiftInfo)
148
149 liftExpr expr@(StgApp v args)
150   = lookUp v            `thenLM` \ ~(sc, sc_args) ->    -- NB the ~.  We don't want to
151                                                         -- poke these bindings too early!
152     returnLM (StgApp sc (map StgVarArg sc_args ++ args),
153               emptyLiftInfo)
154         -- The lvs field is probably wrong, but we reconstruct it
155         -- anyway following lambda lifting
156
157 liftExpr (StgCase scrut lv1 lv2 bndr srt alts)
158   = liftExpr scrut      `thenLM` \ (scrut', scrut_info) ->
159     lift_alts alts      `thenLM` \ (alts', alts_info) ->
160     returnLM (StgCase scrut' lv1 lv2 bndr srt alts', scrut_info `unionLiftInfo` alts_info)
161   where
162     lift_alts (StgAlgAlts ty alg_alts deflt)
163         = mapAndUnzipLM lift_alg_alt alg_alts   `thenLM` \ (alg_alts', alt_infos) ->
164           lift_deflt deflt                      `thenLM` \ (deflt', deflt_info) ->
165           returnLM (StgAlgAlts ty alg_alts' deflt', foldr unionLiftInfo deflt_info alt_infos)
166
167     lift_alts (StgPrimAlts ty prim_alts deflt)
168         = mapAndUnzipLM lift_prim_alt prim_alts `thenLM` \ (prim_alts', alt_infos) ->
169           lift_deflt deflt                      `thenLM` \ (deflt', deflt_info) ->
170           returnLM (StgPrimAlts ty prim_alts' deflt', foldr unionLiftInfo deflt_info alt_infos)
171
172     lift_alg_alt (con, args, use_mask, rhs)
173         = liftExpr rhs          `thenLM` \ (rhs', rhs_info) ->
174           returnLM ((con, args, use_mask, rhs'), rhs_info)
175
176     lift_prim_alt (lit, rhs)
177         = liftExpr rhs  `thenLM` \ (rhs', rhs_info) ->
178           returnLM ((lit, rhs'), rhs_info)
179
180     lift_deflt StgNoDefault = returnLM (StgNoDefault, emptyLiftInfo)
181     lift_deflt (StgBindDefault rhs)
182         = liftExpr rhs  `thenLM` \ (rhs', rhs_info) ->
183           returnLM (StgBindDefault rhs', rhs_info)
184 \end{code}
185
186 Now the interesting cases.  Let no escape isn't lifted.  We turn it
187 back into a let, to play safe, because we have to redo that pass after
188 lambda anyway.
189
190 \begin{code}
191 liftExpr (StgLetNoEscape _ _ (StgNonRec binder rhs) body)
192   = dontLiftRhs rhs     `thenLM` \ (rhs', rhs_info) ->
193     liftExpr body       `thenLM` \ (body', body_info) ->
194     returnLM (StgLet (StgNonRec binder rhs') body',
195               rhs_info `unionLiftInfo` body_info)
196
197 liftExpr (StgLetNoEscape _ _ (StgRec pairs) body)
198   = liftExpr body                       `thenLM` \ (body', body_info) ->
199     mapAndUnzipLM dontLiftRhs rhss      `thenLM` \ (rhss', rhs_infos) ->
200     returnLM (StgLet (StgRec (zipEqual "liftExpr" binders rhss')) body',
201               foldr unionLiftInfo body_info rhs_infos)
202   where
203    (binders,rhss) = unzip pairs
204 \end{code}
205
206 \begin{code}
207 liftExpr (StgLet (StgNonRec binder rhs) body)
208   | not (isLiftable rhs)
209   = dontLiftRhs rhs     `thenLM` \ (rhs', rhs_info) ->
210     liftExpr body       `thenLM` \ (body', body_info) ->
211     returnLM (StgLet (StgNonRec binder rhs') body',
212               rhs_info `unionLiftInfo` body_info)
213
214   | otherwise   -- It's a lambda
215   =     -- Do the body of the let
216     fixLM (\ ~(sc_inline, _, _) ->
217       addScInlines [binder] [sc_inline] (
218         liftExpr body
219       )                 `thenLM` \ (body', body_info) ->
220
221         -- Deal with the RHS
222       dontLiftRhs rhs           `thenLM` \ (rhs', rhs_info) ->
223
224         -- All occurrences in function position, so lambda lift
225       getFinalFreeVars (rhsFreeVars rhs)    `thenLM` \ final_free_vars ->
226
227       mkScPieces final_free_vars (binder,rhs')  `thenLM` \ (sc_inline, sc_bind) ->
228
229       returnLM (sc_inline,
230                 body',
231                 nonRecScBind rhs_info sc_bind `unionLiftInfo` body_info)
232
233     )                   `thenLM` \ (_, expr', final_info) ->
234
235     returnLM (expr', final_info)
236
237 liftExpr (StgLet (StgRec pairs) body)
238 --[Andre-testing]
239   | not (all isLiftableRec rhss)
240   = liftExpr body                       `thenLM` \ (body', body_info) ->
241     mapAndUnzipLM dontLiftRhs rhss      `thenLM` \ (rhss', rhs_infos) ->
242     returnLM (StgLet (StgRec (zipEqual "liftExpr2" binders rhss')) body',
243               foldr unionLiftInfo body_info rhs_infos)
244
245   | otherwise   -- All rhss are liftable
246   = -- Do the body of the let
247     fixLM (\ ~(sc_inlines, _, _) ->
248       addScInlines binders sc_inlines   (
249
250       liftExpr body                     `thenLM` \ (body', body_info) ->
251       mapAndUnzipLM dontLiftRhs rhss    `thenLM` \ (rhss', rhs_infos) ->
252       let
253         -- Find the free vars of all the rhss,
254         -- excluding the binders themselves.
255         rhs_free_vars = unionVarSets (map rhsFreeVars rhss)
256                         `minusVarSet`
257                         mkVarSet binders
258
259         rhs_info      = unionLiftInfos rhs_infos
260       in
261       getFinalFreeVars rhs_free_vars    `thenLM` \ final_free_vars ->
262
263       mapAndUnzipLM (mkScPieces final_free_vars) (binders `zip` rhss')
264                                         `thenLM` \ (sc_inlines, sc_pairs) ->
265       returnLM (sc_inlines,
266                 body',
267                 recScBind rhs_info sc_pairs `unionLiftInfo` body_info)
268
269     ))                  `thenLM` \ (_, expr', final_info) ->
270
271     returnLM (expr', final_info)
272   where
273     (binders,rhss)    = unzip pairs
274 \end{code}
275
276 \begin{code}
277 liftExpr (StgSCC cc expr)
278   = liftExpr expr `thenLM` \ (expr2, expr_info) ->
279     returnLM (StgSCC cc expr2, expr_info)
280 \end{code}
281
282 A binding is liftable if it's a *function* (args not null) and never
283 occurs in an argument position.
284
285 \begin{code}
286 isLiftable :: StgRhs -> Bool
287
288 isLiftable (StgRhsClosure _ (StgBinderInfo arg_occ _ _ _ unapplied_occ) _ fvs _ args _)
289
290   -- Experimental evidence suggests we should lift only if we will be
291   -- abstracting up to 4 fvs.
292
293   = if not (null args   ||      -- Not a function
294          unapplied_occ  ||      -- Has an occ with no args at all
295          arg_occ        ||      -- Occurs in arg position
296          length fvs > 4         -- Too many free variables
297         )
298     then {-trace ("LL: " ++ show (length fvs))-} True
299     else False
300 isLiftable other_rhs = False
301
302 isLiftableRec :: StgRhs -> Bool
303
304 -- this is just the same as for non-rec, except we only lift to
305 -- abstract up to 1 argument this avoids undoing Static Argument
306 -- Transformation work
307
308 {- Andre's longer comment about isLiftableRec: 1996/01:
309
310 A rec binding is "liftable" (according to our heuristics) if:
311 * It is a function,
312 * all occurrences have arguments,
313 * does not occur in an argument position and
314 * has up to *2* free variables (including the rec binding variable
315   itself!)
316
317 The point is: my experiments show that SAT is more important than LL.
318 Therefore if we still want to do LL, for *recursive* functions, we do
319 not want LL to undo what SAT did.  We do this by avoiding LL recursive
320 functions that have more than 2 fvs, since if this recursive function
321 was created by SAT (we don't know!), it would have at least 3 fvs: one
322 for the rec binding itself and 2 more for the static arguments (note:
323 this matches with the choice of performing SAT to have at least 2
324 static arguments, if we change things there we should change things
325 here).
326 -}
327
328 isLiftableRec (StgRhsClosure _ (StgBinderInfo arg_occ _ _ _ unapplied_occ) _ fvs _ args _)
329   = if not (null args   ||      -- Not a function
330          unapplied_occ  ||      -- Has an occ with no args at all
331          arg_occ        ||      -- Occurs in arg position
332          length fvs > 2         -- Too many free variables
333         )
334     then {-trace ("LLRec: " ++ show (length fvs))-} True
335     else False
336 isLiftableRec other_rhs = False
337
338 rhsFreeVars :: StgRhs -> IdSet
339 rhsFreeVars (StgRhsClosure _ _ _ fvs _ _ _) = mkVarSet fvs
340 rhsFreeVars other                         = panic "rhsFreeVars"
341 \end{code}
342
343 dontLiftRhs is like liftExpr, except that it does not lift a top-level
344 lambda abstraction.  It is used for the right-hand sides of
345 definitions where we've decided *not* to lift: for example, top-level
346 ones or mutually-recursive ones where not all are lambdas.
347
348 \begin{code}
349 dontLiftRhs :: StgRhs -> LiftM (StgRhs, LiftInfo)
350
351 dontLiftRhs rhs@(StgRhsCon cc v args) = returnLM (rhs, emptyLiftInfo)
352
353 dontLiftRhs (StgRhsClosure cc bi srt fvs upd args body)
354   = liftExpr body       `thenLM` \ (body', body_info) ->
355     returnLM (StgRhsClosure cc bi srt fvs upd args body', body_info)
356 \end{code}
357
358 \begin{code}
359 mkScPieces :: IdSet             -- Extra args for the supercombinator
360            -> (Id, StgRhs)      -- The processed RHS and original Id
361            -> LiftM ((Id,[Id]),         -- Replace abstraction with this;
362                                                 -- the set is its free vars
363                      (Id,StgRhs))       -- Binding for supercombinator
364
365 mkScPieces extra_arg_set (id, StgRhsClosure cc bi srt _ upd args body)
366   = ASSERT( n_args > 0 )
367         -- Construct the rhs of the supercombinator, and its Id
368     newSupercombinator sc_ty arity  `thenLM` \ sc_id ->
369     returnLM ((sc_id, extra_args), (sc_id, sc_rhs))
370   where
371     n_args     = length args
372     extra_args = varSetElems extra_arg_set
373     arity      = n_args + length extra_args
374
375         -- Construct the supercombinator type
376     type_of_original_id = idType id
377     extra_arg_tys       = map idType extra_args
378     (tyvars, rest)      = splitForAllTys type_of_original_id
379     sc_ty               = mkForAllTys tyvars (mkFunTys extra_arg_tys rest)
380
381     sc_rhs = StgRhsClosure cc bi srt [] upd (extra_args ++ args) body
382 \end{code}
383
384
385 %************************************************************************
386 %*                                                                      *
387 \subsection[Lift-monad]{The LiftM monad}
388 %*                                                                      *
389 %************************************************************************
390
391 The monad is used only to distribute global stuff, and the unique supply.
392
393 \begin{code}
394 type LiftM a =  Module 
395              -> LiftFlags
396              -> UniqSupply
397              -> (IdEnv                          -- Domain = candidates for lifting
398                        (Id,                     -- The supercombinator
399                         [Id])                   -- Args to apply it to
400                  )
401              -> a
402
403
404 type LiftFlags = Maybe Int      -- No of fvs reqd to float recursive
405                                 -- binding; Nothing == infinity
406
407
408 runLM :: Module -> LiftFlags -> UniqSupply -> LiftM a -> a
409 runLM mod flags us m = m mod flags us emptyVarEnv
410
411 thenLM :: LiftM a -> (a -> LiftM b) -> LiftM b
412 thenLM m k mod ci us idenv
413   = k (m mod ci us1 idenv) mod ci us2 idenv
414   where
415     (us1, us2) = splitUniqSupply us
416
417 returnLM :: a -> LiftM a
418 returnLM a mod ci us idenv = a
419
420 fixLM :: (a -> LiftM a) -> LiftM a
421 fixLM k mod ci us idenv = r
422                        where
423                          r = k r mod ci us idenv
424
425 mapLM :: (a -> LiftM b) -> [a] -> LiftM [b]
426 mapLM f [] = returnLM []
427 mapLM f (a:as) = f a            `thenLM` \ r ->
428                  mapLM f as     `thenLM` \ rs ->
429                  returnLM (r:rs)
430
431 mapAndUnzipLM :: (a -> LiftM (b,c)) -> [a] -> LiftM ([b],[c])
432 mapAndUnzipLM f []     = returnLM ([],[])
433 mapAndUnzipLM f (a:as) = f a                    `thenLM` \ (b,c) ->
434                          mapAndUnzipLM f as     `thenLM` \ (bs,cs) ->
435                          returnLM (b:bs, c:cs)
436 \end{code}
437
438 \begin{code}
439 newSupercombinator :: Type
440                    -> Int               -- Arity
441                    -> LiftM Id
442
443 newSupercombinator ty arity mod ci us idenv
444   = setIdVisibility (Just mod) uniq (mkSysLocal uniq ty)
445     `setIdArity` exactArity arity
446         -- ToDo: rm the setIdArity?  Just let subsequent stg-saturation pass do it?
447   where
448     uniq = uniqFromSupply us
449
450 lookUp :: Id -> LiftM (Id,[Id])
451 lookUp v mod ci us idenv
452   = case (lookupVarEnv idenv v) of
453       Just result -> result
454       Nothing     -> (v, [])
455
456 addScInlines :: [Id] -> [(Id,[Id])] -> LiftM a -> LiftM a
457 addScInlines ids values m mod ci us idenv
458   = m mod ci us idenv'
459   where
460     idenv' = extendVarEnvList idenv (ids `zip_lazy` values)
461
462     -- zip_lazy zips two things together but matches lazily on the
463     -- second argument.  This is important, because the ids are know here,
464     -- but the things they are bound to are decided only later
465     zip_lazy [] _           = []
466     zip_lazy (x:xs) ~(y:ys) = (x,y) : zip_lazy xs ys
467
468
469 -- The free vars reported by the free-var analyser will include
470 -- some ids, f, which are to be replaced by ($f a b c), where $f
471 -- is the supercombinator.  Hence instead of f being a free var,
472 -- {a,b,c} are.
473 --
474 -- Example
475 --      let
476 --         f a = ...y1..y2.....
477 --      in
478 --      let
479 --         g b = ...f...z...
480 --      in
481 --      ...
482 --
483 --  Here the free vars of g are {f,z}; but f will be lambda-lifted
484 --  with free vars {y1,y2}, so the "real~ free vars of g are {y1,y2,z}.
485
486 getFinalFreeVars :: IdSet -> LiftM IdSet
487
488 getFinalFreeVars free_vars mod ci us idenv
489   = unionVarSets (map munge_it (varSetElems free_vars))
490   where
491     munge_it :: Id -> IdSet     -- Takes a free var and maps it to the "real"
492                                 -- free var
493     munge_it id = case (lookupVarEnv idenv id) of
494                     Just (_, args) -> mkVarSet args
495                     Nothing        -> unitVarSet id
496 \end{code}
497
498
499 %************************************************************************
500 %*                                                                      *
501 \subsection[Lift-info]{The LiftInfo type}
502 %*                                                                      *
503 %************************************************************************
504
505 \begin{code}
506 type LiftInfo = Bag StgBinding  -- Float to top
507
508 emptyLiftInfo = emptyBag
509
510 unionLiftInfo :: LiftInfo -> LiftInfo -> LiftInfo
511 unionLiftInfo binds1 binds2 = binds1 `unionBags` binds2
512
513 unionLiftInfos :: [LiftInfo] -> LiftInfo
514 unionLiftInfos infos = foldr unionLiftInfo emptyLiftInfo infos
515
516 mkScInfo :: StgBinding -> LiftInfo
517 mkScInfo bind = unitBag bind
518
519 nonRecScBind :: LiftInfo                -- From body of supercombinator
520              -> (Id, StgRhs)    -- Supercombinator and its rhs
521              -> LiftInfo
522 nonRecScBind binds (sc_id,sc_rhs) = binds `snocBag` (StgNonRec sc_id sc_rhs)
523
524
525 -- In the recursive case, all the SCs from the RHSs of the recursive group
526 -- are dealing with might potentially mention the new, recursive SCs.
527 -- So we flatten the whole lot into a single recursive group.
528
529 recScBind :: LiftInfo                   -- From body of supercombinator
530            -> [(Id,StgRhs)]     -- Supercombinator rhs
531            -> LiftInfo
532
533 recScBind binds pairs = unitBag (co_rec_ify (StgRec pairs : bagToList binds))
534
535 co_rec_ify :: [StgBinding] -> StgBinding
536 co_rec_ify binds = StgRec (concat (map f binds))
537   where
538     f (StgNonRec id rhs) = [(id,rhs)]
539     f (StgRec pairs)     = pairs
540
541
542 getScBinds :: LiftInfo -> [StgBinding]
543 getScBinds binds = bagToList binds
544
545 looksLikeSATRhs [(f,StgRhsClosure _ _ _ _ _ ls _)] (StgApp f' args)
546   = (f == f') && (length args == length ls)
547 looksLikeSATRhs _ _ = False
548 \end{code}