4744b33e76b327953e02f395b2dc85ecff5e31dd
[ghc-hetmet.git] / ghc / compiler / simplCore / FloatIn.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
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 CmdLineOpts      ( DynFlags, DynFlag(..), dopt )
20 import CoreSyn
21 import CoreUtils        ( exprIsValue, exprIsDupable )
22 import CoreLint         ( beginPass, endPass )
23 import CoreFVs          ( CoreExprWithFVs, freeVars, freeVarsOf )
24 import Id               ( isOneShotLambda )
25 import Var              ( Id, idType, isTyVar )
26 import Type             ( isUnLiftedType )
27 import VarSet
28 import Util             ( zipEqual, zipWithEqual )
29 import Outputable
30 \end{code}
31
32 Top-level interface function, @floatInwards@.  Note that we do not
33 actually float any bindings downwards from the top-level.
34
35 \begin{code}
36 floatInwards :: DynFlags -> [CoreBind] -> IO [CoreBind]
37
38 floatInwards dflags binds
39   = do {
40         beginPass dflags "Float inwards";
41         let { binds' = map fi_top_bind binds };
42         endPass dflags "Float inwards" 
43                 (dopt Opt_D_verbose_core2core dflags)
44                                 {- no specific flag for dumping float-in -} 
45                 binds'  
46     }
47                           
48   where
49     fi_top_bind (NonRec binder rhs)
50       = NonRec binder (fiExpr [] (freeVars rhs))
51     fi_top_bind (Rec pairs)
52       = Rec [ (b, fiExpr [] (freeVars rhs)) | (b, rhs) <- pairs ]
53 \end{code}
54
55 %************************************************************************
56 %*                                                                      *
57 \subsection{Mail from Andr\'e [edited]}
58 %*                                                                      *
59 %************************************************************************
60
61 {\em Will wrote: What??? I thought the idea was to float as far
62 inwards as possible, no matter what.  This is dropping all bindings
63 every time it sees a lambda of any kind.  Help! }
64
65 You are assuming we DO DO full laziness AFTER floating inwards!  We
66 have to [not float inside lambdas] if we don't.
67
68 If we indeed do full laziness after the floating inwards (we could
69 check the compilation flags for that) then I agree we could be more
70 aggressive and do float inwards past lambdas.
71
72 Actually we are not doing a proper full laziness (see below), which
73 was another reason for not floating inwards past a lambda.
74
75 This can easily be fixed.  The problem is that we float lets outwards,
76 but there are a few expressions which are not let bound, like case
77 scrutinees and case alternatives.  After floating inwards the
78 simplifier could decide to inline the let and the laziness would be
79 lost, e.g.
80
81 \begin{verbatim}
82 let a = expensive             ==> \b -> case expensive of ...
83 in \ b -> case a of ...
84 \end{verbatim}
85 The fix is
86 \begin{enumerate}
87 \item
88 to let bind the algebraic case scrutinees (done, I think) and
89 the case alternatives (except the ones with an
90 unboxed type)(not done, I think). This is best done in the
91 SetLevels.lhs module, which tags things with their level numbers.
92 \item
93 do the full laziness pass (floating lets outwards).
94 \item
95 simplify. The simplifier inlines the (trivial) lets that were
96  created but were not floated outwards.
97 \end{enumerate}
98
99 With the fix I think Will's suggestion that we can gain even more from
100 strictness by floating inwards past lambdas makes sense.
101
102 We still gain even without going past lambdas, as things may be
103 strict in the (new) context of a branch (where it was floated to) or
104 of a let rhs, e.g.
105 \begin{verbatim}
106 let a = something            case x of
107 in case x of                   alt1 -> case something of a -> a + a
108      alt1 -> a + a      ==>    alt2 -> b
109      alt2 -> b
110
111 let a = something           let b = case something of a -> a + a
112 in let b = a + a        ==> in (b,b)
113 in (b,b)
114 \end{verbatim}
115 Also, even if a is not found to be strict in the new context and is
116 still left as a let, if the branch is not taken (or b is not entered)
117 the closure for a is not built.
118
119 %************************************************************************
120 %*                                                                      *
121 \subsection{Main floating-inwards code}
122 %*                                                                      *
123 %************************************************************************
124
125 \begin{code}
126 type FreeVarsSet   = IdSet
127
128 type FloatingBinds = [(CoreBind, FreeVarsSet)]
129         -- In reverse dependency order (innermost bindiner first)
130
131         -- The FreeVarsSet is the free variables of the binding.  In the case
132         -- of recursive bindings, the set doesn't include the bound
133         -- variables.
134
135 fiExpr :: FloatingBinds         -- Binds we're trying to drop
136                                 -- as far "inwards" as possible
137        -> CoreExprWithFVs       -- Input expr
138        -> CoreExpr              -- Result
139
140 fiExpr to_drop (_, AnnVar v) = mkCoLets' to_drop (Var v)
141
142 fiExpr to_drop (_, AnnType ty) = ASSERT( null to_drop )
143                                  Type ty
144
145 fiExpr to_drop (_, AnnLit lit) = Lit lit
146 \end{code}
147
148 Applications: we do float inside applications, mainly because we
149 need to get at all the arguments.  The next simplifier run will
150 pull out any silly ones.
151
152 \begin{code}
153 fiExpr to_drop (_,AnnApp fun arg)
154   = mkCoLets' drop_here (App (fiExpr fun_drop fun) (fiExpr arg_drop arg))
155   where
156     [drop_here, fun_drop, arg_drop] = sepBindsByDropPoint False [freeVarsOf fun, freeVarsOf arg] to_drop
157 \end{code}
158
159 We are careful about lambdas: 
160
161 * We must be careful about floating inside inside a value lambda.  
162   That risks losing laziness.
163   The float-out pass might rescue us, but then again it might not.
164
165 * We must be careful about type lambdas too.  At one time we did, and
166   there is no risk of duplicating work thereby, but we do need to be
167   careful.  In particular, here is a bad case (it happened in the
168   cichelli benchmark:
169         let v = ...
170         in let f = /\t -> \a -> ...
171            ==>
172         let f = /\t -> let v = ... in \a -> ...
173   This is bad as now f is an updatable closure (update PAP)
174   and has arity 0.
175
176 So we treat lambda in groups, using the following rule:
177
178         Float inside a group of lambdas only if
179         they are all either type lambdas or one-shot lambdas.
180
181         Otherwise drop all the bindings outside the group.
182
183 \begin{code}
184 fiExpr to_drop (_, AnnLam b body)
185   = case collect [b] body of
186       (bndrs, real_body)
187         | all is_ok bndrs -> mkLams bndrs (fiExpr to_drop real_body)
188         | otherwise       -> mkCoLets' to_drop (mkLams bndrs (fiExpr [] real_body))
189   where
190     collect bs (_, AnnLam b body) = collect (b:bs) body
191     collect bs body               = (reverse bs, body)
192
193     is_ok bndr = isTyVar bndr || isOneShotLambda bndr
194 \end{code}
195
196 We don't float lets inwards past an SCC.
197         ToDo: keep info on current cc, and when passing
198         one, if it is not the same, annotate all lets in binds with current
199         cc, change current cc to the new one and float binds into expr.
200
201 \begin{code}
202 fiExpr to_drop (_, AnnNote note@(SCC cc) expr)
203   =     -- Wimp out for now
204     mkCoLets' to_drop (Note note (fiExpr [] expr))
205
206 fiExpr to_drop (_, AnnNote InlineCall expr)
207   =     -- Wimp out for InlineCall; keep it close
208         -- the the call it annotates
209     mkCoLets' to_drop (Note InlineCall (fiExpr [] expr))
210
211 fiExpr to_drop (_, AnnNote InlineMe expr)
212   =     -- Ditto... don't float anything into an INLINE expression
213     mkCoLets' to_drop (Note InlineMe (fiExpr [] expr))
214
215 fiExpr to_drop (_, AnnNote note@(Coerce _ _) expr)
216   =     -- Just float in past coercion
217     Note note (fiExpr to_drop expr)
218
219 fiExpr to_drop (_, AnnNote note@(TermUsg _) expr)
220   =     -- Float in past term usage annotation
221         -- (for now; not sure if this is correct: KSW 1999-05)
222     Note note (fiExpr to_drop expr)
223 \end{code}
224
225 For @Lets@, the possible ``drop points'' for the \tr{to_drop}
226 bindings are: (a)~in the body, (b1)~in the RHS of a NonRec binding,
227 or~(b2), in each of the RHSs of the pairs of a @Rec@.
228
229 Note that we do {\em weird things} with this let's binding.  Consider:
230 \begin{verbatim}
231 let
232     w = ...
233 in {
234     let v = ... w ...
235     in ... v .. w ...
236 }
237 \end{verbatim}
238 Look at the inner \tr{let}.  As \tr{w} is used in both the bind and
239 body of the inner let, we could panic and leave \tr{w}'s binding where
240 it is.  But \tr{v} is floatable further into the body of the inner let, and
241 {\em then} \tr{w} will also be only in the body of that inner let.
242
243 So: rather than drop \tr{w}'s binding here, we add it onto the list of
244 things to drop in the outer let's body, and let nature take its
245 course.
246
247 \begin{code}
248 fiExpr to_drop (_,AnnLet (AnnNonRec id rhs@(rhs_fvs, ann_rhs)) body)
249   = fiExpr new_to_drop body
250   where
251     body_fvs = freeVarsOf body
252
253     final_body_fvs | noFloatIntoRhs ann_rhs
254                    || isUnLiftedType (idType id) = body_fvs `unionVarSet` rhs_fvs
255                    | otherwise                   = body_fvs
256         -- See commments with letrec below
257         -- No point in floating in only to float straight out again
258         -- Ditto ok-for-speculation unlifted RHSs
259
260     [shared_binds, rhs_binds, body_binds] = sepBindsByDropPoint False [rhs_fvs, final_body_fvs] to_drop
261
262     new_to_drop = body_binds ++                         -- the bindings used only in the body
263                   [(NonRec id rhs', rhs_fvs')] ++       -- the new binding itself
264                   shared_binds                          -- the bindings used both in rhs and body
265
266         -- Push rhs_binds into the right hand side of the binding
267     rhs'     = fiExpr rhs_binds rhs
268     rhs_fvs' = rhs_fvs `unionVarSet` floatedBindsFVs rhs_binds
269
270 fiExpr to_drop (_,AnnLet (AnnRec bindings) body)
271   = fiExpr new_to_drop body
272   where
273     (binders, rhss) = unzip bindings
274
275     rhss_fvs = map freeVarsOf rhss
276     body_fvs = freeVarsOf body
277
278         -- Add to body_fvs the free vars of any RHS that has
279         -- a lambda at the top.  This has the effect of making it seem
280         -- that such things are used in the body as well, and hence prevents
281         -- them getting floated in.  The big idea is to avoid turning:
282         --      let x# = y# +# 1#
283         --      in
284         --      letrec f = \z. ...x#...f...
285         --      in ...
286         -- into
287         --      letrec f = let x# = y# +# 1# in \z. ...x#...f... in ...
288         -- 
289         -- Because now we can't float the let out again, because a letrec
290         -- can't have unboxed bindings.
291
292     final_body_fvs = foldr (unionVarSet . get_extras) body_fvs rhss
293     get_extras (rhs_fvs, rhs) | noFloatIntoRhs rhs = rhs_fvs
294                               | otherwise          = emptyVarSet
295
296     (shared_binds:body_binds:rhss_binds) = sepBindsByDropPoint False (final_body_fvs:rhss_fvs) to_drop
297
298     new_to_drop = -- the bindings used only in the body
299                   body_binds ++
300                   -- the new binding itself
301                   [(Rec (fi_bind rhss_binds bindings), rhs_fvs')] ++
302                   -- the bindings used both in rhs and body or in more than one rhs
303                   shared_binds
304
305     rhs_fvs' = unionVarSet (unionVarSets rhss_fvs)
306                            (unionVarSets (map floatedBindsFVs rhss_binds))
307
308     -- Push rhs_binds into the right hand side of the binding
309     fi_bind :: [FloatingBinds]      -- one per "drop pt" conjured w/ fvs_of_rhss
310             -> [(Id, CoreExprWithFVs)]
311             -> [(Id, CoreExpr)]
312
313     fi_bind to_drops pairs
314       = [ (binder, fiExpr to_drop rhs) 
315         | ((binder, rhs), to_drop) <- zipEqual "fi_bind" pairs to_drops ]
316 \end{code}
317
318 For @Case@, the possible ``drop points'' for the \tr{to_drop}
319 bindings are: (a)~inside the scrutinee, (b)~inside one of the
320 alternatives/default [default FVs always {\em first}!].
321
322 \begin{code}
323 fiExpr to_drop (_, AnnCase scrut case_bndr alts)
324   = mkCoLets' drop_here1 $
325     mkCoLets' drop_here2 $
326     Case (fiExpr scrut_drops scrut) case_bndr
327          (zipWith fi_alt alts_drops_s alts)
328   where
329         -- Float into the scrut and alts-considered-together just like App
330     [drop_here1, scrut_drops, alts_drops] = sepBindsByDropPoint False [scrut_fvs, all_alts_fvs] to_drop
331
332         -- Float into the alts with the is_case flag set
333     (drop_here2 : alts_drops_s)           = sepBindsByDropPoint True alts_fvs alts_drops
334
335     scrut_fvs    = freeVarsOf scrut
336     alts_fvs     = map alt_fvs alts
337     all_alts_fvs = unionVarSets alts_fvs
338     alt_fvs (con, args, rhs) = foldl delVarSet (freeVarsOf rhs) (case_bndr:args)
339                                 -- Delete case_bndr and args from free vars of rhs 
340                                 -- to get free vars of alt
341
342     fi_alt to_drop (con, args, rhs) = (con, args, fiExpr to_drop rhs)
343
344 noFloatIntoRhs (AnnNote InlineMe _) = True
345 noFloatIntoRhs (AnnLam b _)         = not (isId b && isOneShotLambda b)
346         -- IMPORTANT: don't say 'True' for a RHS with a one-shot lambda at the top.
347         -- This makes a big difference for things like
348         --      f x# = let x = I# x#
349         --             in let j = \() -> ...x...
350         --                in if <condition> then normal-path else j ()
351         -- If x is used only in the error case join point, j, we must float the
352         -- boxing constructor into it, else we box it every time which is very bad
353         -- news indeed.
354
355 noFloatIntoRhs rhs = exprIsValue (deAnnotate' rhs)      -- We'd just float rigt back out again...
356 \end{code}
357
358
359 %************************************************************************
360 %*                                                                      *
361 \subsection{@sepBindsByDropPoint@}
362 %*                                                                      *
363 %************************************************************************
364
365 This is the crucial function.  The idea is: We have a wad of bindings
366 that we'd like to distribute inside a collection of {\em drop points};
367 insides the alternatives of a \tr{case} would be one example of some
368 drop points; the RHS and body of a non-recursive \tr{let} binding
369 would be another (2-element) collection.
370
371 So: We're given a list of sets-of-free-variables, one per drop point,
372 and a list of floating-inwards bindings.  If a binding can go into
373 only one drop point (without suddenly making something out-of-scope),
374 in it goes.  If a binding is used inside {\em multiple} drop points,
375 then it has to go in a you-must-drop-it-above-all-these-drop-points
376 point.
377
378 We have to maintain the order on these drop-point-related lists.
379
380 \begin{code}
381 sepBindsByDropPoint
382     :: Bool                 -- True <=> is case expression
383     -> [FreeVarsSet]        -- One set of FVs per drop point
384     -> FloatingBinds        -- Candidate floaters
385     -> [FloatingBinds]      -- FIRST one is bindings which must not be floated
386                             -- inside any drop point; the rest correspond
387                             -- one-to-one with the input list of FV sets
388
389 -- Every input floater is returned somewhere in the result;
390 -- none are dropped, not even ones which don't seem to be
391 -- free in *any* of the drop-point fvs.  Why?  Because, for example,
392 -- a binding (let x = E in B) might have a specialised version of
393 -- x (say x') stored inside x, but x' isn't free in E or B.
394
395 type DropBox = (FreeVarsSet, FloatingBinds)
396
397 sepBindsByDropPoint is_case drop_pts []
398   = [] : [[] | p <- drop_pts]   -- cut to the chase scene; it happens
399
400 sepBindsByDropPoint is_case drop_pts floaters
401   = go floaters (map (\fvs -> (fvs, [])) (emptyVarSet : drop_pts))
402   where
403     go :: FloatingBinds -> [DropBox] -> [FloatingBinds]
404         -- The *first* one in the argument list is the drop_here set
405         -- The FloatingBinds in the lists are in the reverse of
406         -- the normal FloatingBinds order; that is, they are the right way round!
407
408     go [] drop_boxes = map (reverse . snd) drop_boxes
409
410     go (bind_w_fvs@(bind, bind_fvs) : binds) drop_boxes@(here_box : fork_boxes)
411         = go binds new_boxes
412         where
413           -- "here" means the group of bindings dropped at the top of the fork
414
415           (used_here : used_in_flags) = [ any (`elemVarSet` fvs) (bindersOf bind)
416                                         | (fvs, drops) <- drop_boxes]
417
418           drop_here = used_here || not can_push
419
420                 -- For case expressions we duplicate the binding if it is
421                 -- reasonably small, and if it is not used in all the RHSs
422                 -- This is good for situations like
423                 --      let x = I# y in
424                 --      case e of
425                 --        C -> error x
426                 --        D -> error x
427                 --        E -> ...not mentioning x...
428
429           n_alts      = length used_in_flags
430           n_used_alts = length [() | True <- used_in_flags]
431
432           can_push = n_used_alts == 1           -- Used in just one branch
433                    || (is_case &&               -- We are looking at case alternatives
434                        n_used_alts > 1 &&       -- It's used in more than one
435                        n_used_alts < n_alts &&  -- ...but not all
436                        bindIsDupable bind)      -- and we can duplicate the binding
437
438           new_boxes | drop_here = (insert here_box : fork_boxes)
439                     | otherwise = (here_box : new_fork_boxes)
440
441           new_fork_boxes = zipWithEqual "FloatIn.sepBinds" insert_maybe fork_boxes used_in_flags
442
443           insert :: DropBox -> DropBox
444           insert (fvs,drops) = (fvs `unionVarSet` bind_fvs, bind_w_fvs:drops)
445
446           insert_maybe box True  = insert box
447           insert_maybe box False = box
448
449
450 floatedBindsFVs :: FloatingBinds -> FreeVarsSet
451 floatedBindsFVs binds = unionVarSets (map snd binds)
452
453 mkCoLets' :: FloatingBinds -> CoreExpr -> CoreExpr
454 mkCoLets' to_drop e = foldl (flip (Let . fst)) e to_drop
455         -- Remember to_drop is in *reverse* dependency order
456
457 bindIsDupable (Rec prs)    = all (exprIsDupable . snd) prs
458 bindIsDupable (NonRec b r) = exprIsDupable r
459 \end{code}