[project @ 1998-01-08 18:03:08 by simonm]
[ghc-hetmet.git] / ghc / compiler / simplCore / FloatIn.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 %************************************************************************
5 %*                                                                      *
6 \section[FloatIn]{Floating Inwards pass}
7 %*                                                                      *
8 %************************************************************************
9
10 The main purpose of @floatInwards@ is floating into branches of a
11 case, so that we don't allocate things, save them on the stack, and
12 then discover that they aren't needed in the chosen branch.
13
14 \begin{code}
15 module FloatIn ( floatInwards ) where
16
17 #include "HsVersions.h"
18
19 import AnnCoreSyn
20 import CoreSyn
21
22 import FreeVars
23 import Id               ( emptyIdSet, unionIdSets, unionManyIdSets,
24                           elementOfIdSet, IdSet, GenId, Id
25                         )
26 import Util             ( nOfThem, panic, zipEqual )
27 \end{code}
28
29 Top-level interface function, @floatInwards@.  Note that we do not
30 actually float any bindings downwards from the top-level.
31
32 \begin{code}
33 floatInwards :: [CoreBinding] -> [CoreBinding]
34
35 floatInwards binds
36   = map fi_top_bind binds
37   where
38     fi_top_bind (NonRec binder rhs)
39       = NonRec binder (fiExpr [] (freeVars rhs))
40     fi_top_bind (Rec pairs)
41       = Rec [ (b, fiExpr [] (freeVars rhs)) | (b, rhs) <- pairs ]
42 \end{code}
43
44 %************************************************************************
45 %*                                                                      *
46 \subsection{Mail from Andr\'e [edited]}
47 %*                                                                      *
48 %************************************************************************
49
50 {\em Will wrote: What??? I thought the idea was to float as far
51 inwards as possible, no matter what.  This is dropping all bindings
52 every time it sees a lambda of any kind.  Help! }
53
54 You are assuming we DO DO full laziness AFTER floating inwards!  We
55 have to [not float inside lambdas] if we don't.
56
57 If we indeed do full laziness after the floating inwards (we could
58 check the compilation flags for that) then I agree we could be more
59 aggressive and do float inwards past lambdas.
60
61 Actually we are not doing a proper full laziness (see below), which
62 was another reason for not floating inwards past a lambda.
63
64 This can easily be fixed.
65 The problem is that we float lets outwards,
66 but there are a few expressions which are not
67 let bound, like case scrutinees and case alternatives.
68 After floating inwards the simplifier could decide to inline
69 the let and the laziness would be lost, e.g.
70 \begin{verbatim}
71 let a = expensive             ==> \b -> case expensive of ...
72 in \ b -> case a of ...
73 \end{verbatim}
74 The fix is
75 \begin{enumerate}
76 \item
77 to let bind the algebraic case scrutinees (done, I think) and
78 the case alternatives (except the ones with an
79 unboxed type)(not done, I think). This is best done in the
80 SetLevels.lhs module, which tags things with their level numbers.
81 \item
82 do the full laziness pass (floating lets outwards).
83 \item
84 simplify. The simplifier inlines the (trivial) lets that were
85  created but were not floated outwards.
86 \end{enumerate}
87
88 With the fix I think Will's suggestion that we can gain even more from
89 strictness by floating inwards past lambdas makes sense.
90
91 We still gain even without going past lambdas, as things may be
92 strict in the (new) context of a branch (where it was floated to) or
93 of a let rhs, e.g.
94 \begin{verbatim}
95 let a = something            case x of
96 in case x of                   alt1 -> case something of a -> a + a
97      alt1 -> a + a      ==>    alt2 -> b
98      alt2 -> b
99
100 let a = something           let b = case something of a -> a + a
101 in let b = a + a        ==> in (b,b)
102 in (b,b)
103 \end{verbatim}
104 Also, even if a is not found to be strict in the new context and is
105 still left as a let, if the branch is not taken (or b is not entered)
106 the closure for a is not built.
107
108 %************************************************************************
109 %*                                                                      *
110 \subsection{Main floating-inwards code}
111 %*                                                                      *
112 %************************************************************************
113
114 \begin{code}
115 type FreeVarsSet   = IdSet
116
117 type FloatingBinds = [(CoreBinding, FreeVarsSet)]
118         -- In dependency order (outermost first)
119
120         -- The FreeVarsSet is the free variables of the binding.  In the case
121         -- of recursive bindings, the set doesn't include the bound
122         -- variables.
123
124 fiExpr :: FloatingBinds         -- binds we're trying to drop
125                                 -- as far "inwards" as possible
126        -> CoreExprWithFVs       -- input expr
127        -> CoreExpr              -- result
128
129 fiExpr to_drop (_,AnnVar v) = mkCoLets' to_drop (Var v)
130
131 fiExpr to_drop (_,AnnLit k) = mkCoLets' to_drop (Lit k)
132
133 fiExpr to_drop (_,AnnCon c atoms)
134   = mkCoLets' to_drop (Con c atoms)
135
136 fiExpr to_drop (_,AnnPrim c atoms)
137   = mkCoLets' to_drop (Prim c atoms)
138 \end{code}
139
140 Here we are not floating inside lambda (type lambdas are OK):
141 \begin{code}
142 fiExpr to_drop (_,AnnLam b@(ValBinder binder) body)
143   = mkCoLets' to_drop (Lam b (fiExpr [] body))
144
145 fiExpr to_drop (_,AnnLam b@(TyBinder tyvar) body)
146   | whnf body
147   -- we do not float into type lambdas if they are followed by
148   -- a whnf (actually we check for lambdas and constructors).
149   -- The reason is that a let binding will get stuck
150   -- in between the type lambda and the whnf and the simplifier
151   -- does not know how to pull it back out from a type lambda.
152   -- Ex:
153   --    let v = ...
154   --    in let f = /\t -> \a -> ...
155   --       ==>
156   --    let f = /\t -> let v = ... in \a -> ...
157   -- which is bad as now f is an updatable closure (update PAP)
158   -- and has arity 0. This example comes from cichelli.
159
160   = mkCoLets' to_drop (Lam b (fiExpr [] body))
161   | otherwise
162   = Lam b (fiExpr to_drop body)
163   where
164     whnf :: CoreExprWithFVs -> Bool
165
166     whnf (_,AnnLit _)   = True
167     whnf (_,AnnCon _ _) = True
168     whnf (_,AnnLam x e) = if isValBinder x then True else whnf e
169     whnf (_,AnnSCC _ e) = whnf e
170     whnf _              = False
171 \end{code}
172
173 Applications: we could float inside applications, but it's probably
174 not worth it (a purely practical choice, hunch- [not experience-]
175 based).
176 \begin{code}
177 fiExpr to_drop (_,AnnApp fun arg)
178   | isValArg arg
179   = mkCoLets' to_drop (App (fiExpr [] fun) arg)
180   | otherwise
181   = App (fiExpr to_drop fun) arg
182 \end{code}
183
184 We don't float lets inwards past an SCC.
185
186 ToDo: SCC: {\em should} keep info on current cc, and when passing
187 one, if it is not the same, annotate all lets in binds with current
188 cc, change current cc to the new one and float binds into expr.
189 \begin{code}
190 fiExpr to_drop (_, AnnSCC cc expr)
191   = mkCoLets' to_drop (SCC cc (fiExpr [] expr))
192 \end{code}
193
194 \begin{code}
195 fiExpr to_drop (_, AnnCoerce c ty expr)
196   = --trace "fiExpr:Coerce:wimping out" $
197     mkCoLets' to_drop (Coerce c ty (fiExpr [] expr))
198 \end{code}
199
200 For @Lets@, the possible ``drop points'' for the \tr{to_drop}
201 bindings are: (a)~in the body, (b1)~in the RHS of a NonRec binding,
202 or~(b2), in each of the RHSs of the pairs of a @Rec@.
203
204 Note that we do {\em weird things} with this let's binding.  Consider:
205 \begin{verbatim}
206 let
207     w = ...
208 in {
209     let v = ... w ...
210     in ... w ...
211 }
212 \end{verbatim}
213 Look at the inner \tr{let}.  As \tr{w} is used in both the bind and
214 body of the inner let, we could panic and leave \tr{w}'s binding where
215 it is.  But \tr{v} is floatable into the body of the inner let, and
216 {\em then} \tr{w} will also be only in the body of that inner let.
217
218 So: rather than drop \tr{w}'s binding here, we add it onto the list of
219 things to drop in the outer let's body, and let nature take its
220 course.
221
222 \begin{code}
223 fiExpr to_drop (_,AnnLet (AnnNonRec id rhs) body)
224   = fiExpr new_to_drop body
225   where
226     rhs_fvs  = freeVarsOf rhs
227     body_fvs = freeVarsOf body
228
229     ([rhs_binds, body_binds], shared_binds) = sepBindsByDropPoint [rhs_fvs, body_fvs] to_drop
230
231     new_to_drop = body_binds ++                         -- the bindings used only in the body
232                   [(NonRec id rhs', rhs_fvs')] ++       -- the new binding itself
233                   shared_binds                          -- the bindings used both in rhs and body
234
235         -- Push rhs_binds into the right hand side of the binding
236     rhs'     = fiExpr rhs_binds rhs
237     rhs_fvs' = rhs_fvs `unionIdSets` floatedBindsFVs rhs_binds
238
239 fiExpr to_drop (_,AnnLet (AnnRec bindings) body)
240   = fiExpr new_to_drop body
241   where
242     (binders, rhss) = unzip bindings
243
244     rhss_fvs = map freeVarsOf rhss
245     body_fvs = freeVarsOf body
246
247     (body_binds:rhss_binds, shared_binds)
248       = sepBindsByDropPoint (body_fvs:rhss_fvs) to_drop
249
250     new_to_drop = -- the bindings used only in the body
251                   body_binds ++
252                   -- the new binding itself
253                   [(Rec (fi_bind rhss_binds bindings), rhs_fvs')] ++
254                   -- the bindings used both in rhs and body or in more than one rhs
255                   shared_binds
256
257     rhs_fvs' = unionIdSets (unionManyIdSets rhss_fvs)
258                      (unionManyIdSets (map floatedBindsFVs rhss_binds))
259
260     -- Push rhs_binds into the right hand side of the binding
261     fi_bind :: [FloatingBinds]      -- one per "drop pt" conjured w/ fvs_of_rhss
262             -> [(Id, CoreExprWithFVs)]
263             -> [(Id, CoreExpr)]
264
265     fi_bind to_drops pairs
266       = [ (binder, fiExpr to_drop rhs) | ((binder, rhs), to_drop) <- zipEqual "fi_bind" pairs to_drops ]
267 \end{code}
268
269 For @Case@, the possible ``drop points'' for the \tr{to_drop}
270 bindings are: (a)~inside the scrutinee, (b)~inside one of the
271 alternatives/default [default FVs always {\em first}!].
272
273 \begin{code}
274 fiExpr to_drop (_, AnnCase scrut alts)
275   = let
276         fvs_scrut    = freeVarsOf scrut
277         drop_pts_fvs = fvs_scrut : (get_fvs_from_deflt_and_alts alts)
278     in
279     case (sepBindsByDropPoint drop_pts_fvs to_drop)
280                 of (scrut_drops : deflt_drops : alts_drops, drop_here) ->
281                      mkCoLets' drop_here (Case (fiExpr scrut_drops scrut)
282                                                 (fi_alts deflt_drops alts_drops alts))
283
284   where
285     ----------------------------
286     -- pin default FVs on first!
287     --
288     get_fvs_from_deflt_and_alts (AnnAlgAlts alts deflt)
289       = get_deflt_fvs deflt : [ freeVarsOf rhs | (_, _, rhs) <- alts ]
290
291     get_fvs_from_deflt_and_alts (AnnPrimAlts alts deflt)
292       = get_deflt_fvs deflt : [ freeVarsOf rhs | (_, rhs) <- alts]
293
294     get_deflt_fvs AnnNoDefault     = emptyIdSet
295     get_deflt_fvs (AnnBindDefault b rhs) = freeVarsOf rhs
296
297     ----------------------------
298     fi_alts to_drop_deflt to_drop_alts (AnnAlgAlts alts deflt)
299       = AlgAlts
300             [ (con, params, fiExpr to_drop rhs)
301             | ((con, params, rhs), to_drop) <- zipEqual "fi_alts" alts to_drop_alts ]
302             (fi_default to_drop_deflt deflt)
303
304     fi_alts to_drop_deflt to_drop_alts (AnnPrimAlts alts deflt)
305       = PrimAlts
306             [ (lit, fiExpr to_drop rhs)
307             | ((lit, rhs), to_drop) <- zipEqual "fi_alts2" alts to_drop_alts ]
308             (fi_default to_drop_deflt deflt)
309
310     fi_default to_drop AnnNoDefault           = NoDefault
311     fi_default to_drop (AnnBindDefault b e) = BindDefault b (fiExpr to_drop e)
312 \end{code}
313
314 %************************************************************************
315 %*                                                                      *
316 \subsection{@sepBindsByDropPoint@}
317 %*                                                                      *
318 %************************************************************************
319
320 This is the crucial function.  The idea is: We have a wad of bindings
321 that we'd like to distribute inside a collection of {\em drop points};
322 insides the alternatives of a \tr{case} would be one example of some
323 drop points; the RHS and body of a non-recursive \tr{let} binding
324 would be another (2-element) collection.
325
326 So: We're given a list of sets-of-free-variables, one per drop point,
327 and a list of floating-inwards bindings.  If a binding can go into
328 only one drop point (without suddenly making something out-of-scope),
329 in it goes.  If a binding is used inside {\em multiple} drop points,
330 then it has to go in a you-must-drop-it-above-all-these-drop-points
331 point.
332
333 We have to maintain the order on these drop-point-related lists.
334
335 \begin{code}
336 sepBindsByDropPoint
337     :: [FreeVarsSet]        -- one set of FVs per drop point
338     -> FloatingBinds        -- candidate floaters
339     -> ([FloatingBinds],    -- floaters that *can* be floated into
340                             -- the corresponding drop point
341         FloatingBinds)      -- everything else, bindings which must
342                             -- not be floated inside any drop point
343
344 sepBindsByDropPoint drop_pts []
345   = ([[] | p <- drop_pts], []) -- cut to the chase scene; it happens
346
347 sepBindsByDropPoint drop_pts floaters
348   = let
349         (per_drop_pt, must_stay_here, _)
350             --= sep drop_pts emptyIdSet{-fvs of prev drop_pts-} floaters
351             = split' drop_pts floaters [] empty_boxes
352         empty_boxes = nOfThem (length drop_pts) []
353     in
354     (map reverse per_drop_pt, reverse must_stay_here)
355   where
356     split' drop_pts_fvs [] mult_branch drop_boxes
357       = (drop_boxes, mult_branch, drop_pts_fvs)
358
359     -- only in a or unused
360     split' (a:as) (bind:binds) mult_branch (drop_box_a:drop_boxes)
361       | all (\b -> {-b `elementOfIdSet` a &&-}
362                    not (b `elementOfIdSet` (unionManyIdSets as)))
363             (bindersOf (fst bind))
364       = split' (a':as) binds mult_branch ((bind:drop_box_a):drop_boxes)
365       where
366         a' = a `unionIdSets` fvsOfBind bind
367
368     -- not in a
369     split' (a:as) (bind:binds) mult_branch (drop_box_a:drop_boxes)
370       | all (\b -> not (b `elementOfIdSet` a)) (bindersOf (fst bind))
371       = split' (a:as') binds mult_branch' (drop_box_a:drop_boxes')
372       where
373         (drop_boxes',mult_branch',as') = split' as [bind] mult_branch drop_boxes
374
375     -- in a and in as
376     split' aas@(a:as) (bind:binds) mult_branch drop_boxes
377       = split' aas' binds (bind : mult_branch) drop_boxes
378       where
379         aas' = map (unionIdSets (fvsOfBind bind)) aas
380
381     -------------------------
382     fvsOfBind (_,fvs)   = fvs
383
384 floatedBindsFVs :: FloatingBinds -> FreeVarsSet
385 floatedBindsFVs binds = unionManyIdSets (map snd binds)
386
387 mkCoLets' :: FloatingBinds -> CoreExpr -> CoreExpr
388 mkCoLets' to_drop e = mkCoLetsNoUnboxed (reverse (map fst to_drop)) e
389 \end{code}