Add (a) CoreM monad, (b) new Annotations feature
[ghc-hetmet.git] / compiler / simplCore / FloatOut.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[FloatOut]{Float bindings outwards (towards the top level)}
5
6 ``Long-distance'' floating of bindings towards the top level.
7
8 \begin{code}
9 module FloatOut ( floatOutwards ) where
10
11 import CoreSyn
12 import CoreUtils
13
14 import DynFlags ( DynFlags, DynFlag(..), FloatOutSwitches(..) )
15 import ErrUtils         ( dumpIfSet_dyn )
16 import CostCentre       ( dupifyCC, CostCentre )
17 import Id               ( Id, idType )
18 import Type             ( isUnLiftedType )
19 import SetLevels        ( Level(..), LevelledExpr, LevelledBind,
20                           setLevels, ltMajLvl, ltLvl, isTopLvl )
21 import UniqSupply       ( UniqSupply )
22 import List             ( partition )
23 import Outputable
24 import FastString
25 \end{code}
26
27         -----------------
28         Overall game plan
29         -----------------
30
31 The Big Main Idea is:
32
33         To float out sub-expressions that can thereby get outside
34         a non-one-shot value lambda, and hence may be shared.
35
36
37 To achieve this we may need to do two thing:
38
39    a) Let-bind the sub-expression:
40
41         f (g x)  ==>  let lvl = f (g x) in lvl
42
43       Now we can float the binding for 'lvl'.  
44
45    b) More than that, we may need to abstract wrt a type variable
46
47         \x -> ... /\a -> let v = ...a... in ....
48
49       Here the binding for v mentions 'a' but not 'x'.  So we
50       abstract wrt 'a', to give this binding for 'v':
51
52             vp = /\a -> ...a...
53             v  = vp a
54
55       Now the binding for vp can float out unimpeded.
56       I can't remember why this case seemed important enough to
57       deal with, but I certainly found cases where important floats
58       didn't happen if we did not abstract wrt tyvars.
59
60 With this in mind we can also achieve another goal: lambda lifting.
61 We can make an arbitrary (function) binding float to top level by
62 abstracting wrt *all* local variables, not just type variables, leaving
63 a binding that can be floated right to top level.  Whether or not this
64 happens is controlled by a flag.
65
66
67 Random comments
68 ~~~~~~~~~~~~~~~
69
70 At the moment we never float a binding out to between two adjacent
71 lambdas.  For example:
72
73 @
74         \x y -> let t = x+x in ...
75 ===>
76         \x -> let t = x+x in \y -> ...
77 @
78 Reason: this is less efficient in the case where the original lambda
79 is never partially applied.
80
81 But there's a case I've seen where this might not be true.  Consider:
82 @
83 elEm2 x ys
84   = elem' x ys
85   where
86     elem' _ []  = False
87     elem' x (y:ys)      = x==y || elem' x ys
88 @
89 It turns out that this generates a subexpression of the form
90 @
91         \deq x ys -> let eq = eqFromEqDict deq in ...
92 @
93 vwhich might usefully be separated to
94 @
95         \deq -> let eq = eqFromEqDict deq in \xy -> ...
96 @
97 Well, maybe.  We don't do this at the moment.
98
99 \begin{code}
100 type FloatBind     = (Level, CoreBind)  -- INVARIANT: a FloatBind is always lifted
101 type FloatBinds    = [FloatBind]        
102 \end{code}
103
104 %************************************************************************
105 %*                                                                      *
106 \subsection[floatOutwards]{@floatOutwards@: let-floating interface function}
107 %*                                                                      *
108 %************************************************************************
109
110 \begin{code}
111 floatOutwards :: FloatOutSwitches
112               -> DynFlags
113               -> UniqSupply 
114               -> [CoreBind] -> IO [CoreBind]
115
116 floatOutwards float_sws dflags us pgm
117   = do {
118         let { annotated_w_levels = setLevels float_sws pgm us ;
119               (fss, binds_s')    = unzip (map floatTopBind annotated_w_levels)
120             } ;
121
122         dumpIfSet_dyn dflags Opt_D_verbose_core2core "Levels added:"
123                   (vcat (map ppr annotated_w_levels));
124
125         let { (tlets, ntlets, lams) = get_stats (sum_stats fss) };
126
127         dumpIfSet_dyn dflags Opt_D_dump_simpl_stats "FloatOut stats:"
128                 (hcat [ int tlets,  ptext (sLit " Lets floated to top level; "),
129                         int ntlets, ptext (sLit " Lets floated elsewhere; from "),
130                         int lams,   ptext (sLit " Lambda groups")]);
131
132         return (concat binds_s')
133     }
134
135 floatTopBind :: LevelledBind -> (FloatStats, [CoreBind])
136 floatTopBind bind
137   = case (floatBind bind) of { (fs, floats) ->
138     (fs, floatsToBinds floats)
139     }
140 \end{code}
141
142 %************************************************************************
143 %*                                                                      *
144 \subsection[FloatOut-Bind]{Floating in a binding (the business end)}
145 %*                                                                      *
146 %************************************************************************
147
148
149 \begin{code}
150 floatBind :: LevelledBind -> (FloatStats, FloatBinds)
151
152 floatBind (NonRec (TB name level) rhs)
153   = case (floatRhs level rhs) of { (fs, rhs_floats, rhs') ->
154     (fs, rhs_floats ++ [(level, NonRec name rhs')]) }
155
156 floatBind bind@(Rec pairs)
157   = case (unzip3 (map do_pair pairs)) of { (fss, rhss_floats, new_pairs) ->
158     let rhs_floats = concat rhss_floats in
159
160     if not (isTopLvl bind_dest_lvl) then
161         -- Find which bindings float out at least one lambda beyond this one
162         -- These ones can't mention the binders, because they couldn't 
163         -- be escaping a major level if so.
164         -- The ones that are not going further can join the letrec;
165         -- they may not be mutually recursive but the occurrence analyser will
166         -- find that out.
167         case (partitionByMajorLevel bind_dest_lvl rhs_floats) of { (floats', heres) ->
168         (sum_stats fss, floats' ++ [(bind_dest_lvl, Rec (floatsToBindPairs heres ++ new_pairs))]) }
169     else
170         -- In a recursive binding, *destined for* the top level
171         -- (only), the rhs floats may contain references to the 
172         -- bound things.  For example
173         --      f = ...(let v = ...f... in b) ...
174         --  might get floated to
175         --      v = ...f...
176         --      f = ... b ...
177         -- and hence we must (pessimistically) make all the floats recursive
178         -- with the top binding.  Later dependency analysis will unravel it.
179         --
180         -- This can only happen for bindings destined for the top level,
181         -- because only then will partitionByMajorLevel allow through a binding
182         -- that only differs in its minor level
183         (sum_stats fss, [(bind_dest_lvl, Rec (new_pairs ++ floatsToBindPairs rhs_floats))])
184     }
185   where
186     bind_dest_lvl = getBindLevel bind
187
188     do_pair (TB name level, rhs)
189       = case (floatRhs level rhs) of { (fs, rhs_floats, rhs') ->
190         (fs, rhs_floats, (name, rhs'))
191         }
192 \end{code}
193
194 %************************************************************************
195
196 \subsection[FloatOut-Expr]{Floating in expressions}
197 %*                                                                      *
198 %************************************************************************
199
200 \begin{code}
201 floatExpr, floatRhs, floatCaseAlt
202          :: Level
203          -> LevelledExpr
204          -> (FloatStats, FloatBinds, CoreExpr)
205
206 floatCaseAlt lvl arg    -- Used rec rhss, and case-alternative rhss
207   = case (floatExpr lvl arg) of { (fsa, floats, arg') ->
208     case (partitionByMajorLevel lvl floats) of { (floats', heres) ->
209         -- Dump bindings that aren't going to escape from a lambda;
210         -- in particular, we must dump the ones that are bound by 
211         -- the rec or case alternative
212     (fsa, floats', install heres arg') }}
213
214 floatRhs lvl arg        -- Used for nested non-rec rhss, and fn args
215                         -- See Note [Floating out of RHS]
216   = case (floatExpr lvl arg) of { (fsa, floats, arg') ->
217     if exprIsCheap arg' then    
218         (fsa, floats, arg')
219     else
220     case (partitionByMajorLevel lvl floats) of { (floats', heres) ->
221     (fsa, floats', install heres arg') }}
222
223 -- Note [Floating out of RHSs]
224 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~
225 -- Dump bindings that aren't going to escape from a lambda
226 -- This isn't a scoping issue (the binder isn't in scope in the RHS 
227 --      of a non-rec binding)
228 -- Rather, it is to avoid floating the x binding out of
229 --      f (let x = e in b)
230 -- unnecessarily.  But we first test for values or trival rhss,
231 -- because (in particular) we don't want to insert new bindings between
232 -- the "=" and the "\".  E.g.
233 --      f = \x -> let <bind> in <body>
234 -- We do not want
235 --      f = let <bind> in \x -> <body>
236 -- (a) The simplifier will immediately float it further out, so we may
237 --      as well do so right now; in general, keeping rhss as manifest 
238 --      values is good
239 -- (b) If a float-in pass follows immediately, it might add yet more
240 --      bindings just after the '='.  And some of them might (correctly)
241 --      be strict even though the 'let f' is lazy, because f, being a value,
242 --      gets its demand-info zapped by the simplifier.
243 --
244 -- We use exprIsCheap because that is also what's used by the simplifier
245 -- to decide whether to float a let out of a let
246
247 floatExpr _ (Var v)   = (zeroStats, [], Var v)
248 floatExpr _ (Type ty) = (zeroStats, [], Type ty)
249 floatExpr _ (Lit lit) = (zeroStats, [], Lit lit)
250           
251 floatExpr lvl (App e a)
252   = case (floatExpr      lvl e) of { (fse, floats_e, e') ->
253     case (floatRhs lvl a)       of { (fsa, floats_a, a') ->
254     (fse `add_stats` fsa, floats_e ++ floats_a, App e' a') }}
255
256 floatExpr _ lam@(Lam _ _)
257   = let
258         (bndrs_w_lvls, body) = collectBinders lam
259         bndrs                = [b | TB b _ <- bndrs_w_lvls]
260         lvls                 = [l | TB _ l <- bndrs_w_lvls]
261
262         -- For the all-tyvar case we are prepared to pull 
263         -- the lets out, to implement the float-out-of-big-lambda
264         -- transform; but otherwise we only float bindings that are
265         -- going to escape a value lambda.
266         -- In particular, for one-shot lambdas we don't float things
267         -- out; we get no saving by so doing.
268         partition_fn | all isTyVar bndrs = partitionByLevel
269                      | otherwise         = partitionByMajorLevel
270     in
271     case (floatExpr (last lvls) body) of { (fs, floats, body') ->
272
273         -- Dump any bindings which absolutely cannot go any further
274     case (partition_fn (head lvls) floats)      of { (floats', heres) ->
275
276     (add_to_stats fs floats', floats', mkLams bndrs (install heres body'))
277     }}
278
279 floatExpr lvl (Note note@(SCC cc) expr)
280   = case (floatExpr lvl expr)    of { (fs, floating_defns, expr') ->
281     let
282         -- Annotate bindings floated outwards past an scc expression
283         -- with the cc.  We mark that cc as "duplicated", though.
284
285         annotated_defns = annotate (dupifyCC cc) floating_defns
286     in
287     (fs, annotated_defns, Note note expr') }
288   where
289     annotate :: CostCentre -> FloatBinds -> FloatBinds
290
291     annotate dupd_cc defn_groups
292       = [ (level, ann_bind floater) | (level, floater) <- defn_groups ]
293       where
294         ann_bind (NonRec binder rhs)
295           = NonRec binder (mkSCC dupd_cc rhs)
296
297         ann_bind (Rec pairs)
298           = Rec [(binder, mkSCC dupd_cc rhs) | (binder, rhs) <- pairs]
299
300 floatExpr _ (Note InlineMe expr)        -- Other than SCCs
301   = (zeroStats, [], Note InlineMe (unTag expr))
302         -- Do no floating at all inside INLINE.
303         -- The SetLevels pass did not clone the bindings, so it's
304         -- unsafe to do any floating, even if we dump the results
305         -- inside the Note (which is what we used to do).
306
307 floatExpr lvl (Note note expr)  -- Other than SCCs
308   = case (floatExpr lvl expr)    of { (fs, floating_defns, expr') ->
309     (fs, floating_defns, Note note expr') }
310
311 floatExpr lvl (Cast expr co)
312   = case (floatExpr lvl expr)   of { (fs, floating_defns, expr') ->
313     (fs, floating_defns, Cast expr' co) }
314
315 floatExpr lvl (Let (NonRec (TB bndr bndr_lvl) rhs) body)
316   | isUnLiftedType (idType bndr)        -- Treat unlifted lets just like a case
317                                 -- I.e. floatExpr for rhs, floatCaseAlt for body
318   = case floatExpr lvl rhs          of { (_, rhs_floats, rhs') ->
319     case floatCaseAlt bndr_lvl body of { (fs, body_floats, body') ->
320     (fs, rhs_floats ++ body_floats, Let (NonRec bndr rhs') body') }}
321
322 floatExpr lvl (Let bind body)
323   = case (floatBind bind)     of { (fsb, bind_floats) ->
324     case (floatExpr lvl body) of { (fse, body_floats, body') ->
325     (add_stats fsb fse,
326      bind_floats ++ body_floats,
327      body')  }}
328
329 floatExpr lvl (Case scrut (TB case_bndr case_lvl) ty alts)
330   = case floatExpr lvl scrut    of { (fse, fde, scrut') ->
331     case floatList float_alt alts       of { (fsa, fda, alts')  ->
332     (add_stats fse fsa, fda ++ fde, Case scrut' case_bndr ty alts')
333     }}
334   where
335         -- Use floatCaseAlt for the alternatives, so that we
336         -- don't gratuitiously float bindings out of the RHSs
337     float_alt (con, bs, rhs)
338         = case (floatCaseAlt case_lvl rhs)      of { (fs, rhs_floats, rhs') ->
339           (fs, rhs_floats, (con, [b | TB b _ <- bs], rhs')) }
340
341
342 floatList :: (a -> (FloatStats, FloatBinds, b)) -> [a] -> (FloatStats, FloatBinds, [b])
343 floatList _ [] = (zeroStats, [], [])
344 floatList f (a:as) = case f a            of { (fs_a,  binds_a,  b)  ->
345                      case floatList f as of { (fs_as, binds_as, bs) ->
346                      (fs_a `add_stats` fs_as, binds_a ++ binds_as, b:bs) }}
347
348 unTagBndr :: TaggedBndr tag -> CoreBndr
349 unTagBndr (TB b _) = b
350
351 unTag :: TaggedExpr tag -> CoreExpr
352 unTag (Var v)     = Var v
353 unTag (Lit l)     = Lit l
354 unTag (Type ty)   = Type ty
355 unTag (Note n e)  = Note n (unTag e)
356 unTag (App e1 e2) = App (unTag e1) (unTag e2)
357 unTag (Lam b e)   = Lam (unTagBndr b) (unTag e)
358 unTag (Cast e co) = Cast (unTag e) co
359 unTag (Let (Rec prs) e)    = Let (Rec [(unTagBndr b,unTag r) | (b, r) <- prs]) (unTag e)
360 unTag (Let (NonRec b r) e) = Let (NonRec (unTagBndr b) (unTag r)) (unTag e)
361 unTag (Case e b ty alts)   = Case (unTag e) (unTagBndr b) ty
362                                   [(c, map unTagBndr bs, unTag r) | (c,bs,r) <- alts]
363 \end{code}
364
365 %************************************************************************
366 %*                                                                      *
367 \subsection{Utility bits for floating stats}
368 %*                                                                      *
369 %************************************************************************
370
371 I didn't implement this with unboxed numbers.  I don't want to be too
372 strict in this stuff, as it is rarely turned on.  (WDP 95/09)
373
374 \begin{code}
375 data FloatStats
376   = FlS Int  -- Number of top-floats * lambda groups they've been past
377         Int  -- Number of non-top-floats * lambda groups they've been past
378         Int  -- Number of lambda (groups) seen
379
380 get_stats :: FloatStats -> (Int, Int, Int)
381 get_stats (FlS a b c) = (a, b, c)
382
383 zeroStats :: FloatStats
384 zeroStats = FlS 0 0 0
385
386 sum_stats :: [FloatStats] -> FloatStats
387 sum_stats xs = foldr add_stats zeroStats xs
388
389 add_stats :: FloatStats -> FloatStats -> FloatStats
390 add_stats (FlS a1 b1 c1) (FlS a2 b2 c2)
391   = FlS (a1 + a2) (b1 + b2) (c1 + c2)
392
393 add_to_stats :: FloatStats -> [(Level, Bind CoreBndr)] -> FloatStats
394 add_to_stats (FlS a b c) floats
395   = FlS (a + length top_floats) (b + length other_floats) (c + 1)
396   where
397     (top_floats, other_floats) = partition to_very_top floats
398
399     to_very_top (my_lvl, _) = isTopLvl my_lvl
400 \end{code}
401
402
403 %************************************************************************
404 %*                                                                      *
405 \subsection{Utility bits for floating}
406 %*                                                                      *
407 %************************************************************************
408
409 \begin{code}
410 getBindLevel :: Bind (TaggedBndr Level) -> Level
411 getBindLevel (NonRec (TB _ lvl) _)       = lvl
412 getBindLevel (Rec (((TB _ lvl), _) : _)) = lvl
413 getBindLevel (Rec [])                    = panic "getBindLevel Rec []"
414 \end{code}
415
416 \begin{code}
417 partitionByMajorLevel, partitionByLevel
418         :: Level                -- Partitioning level
419
420         -> FloatBinds           -- Defns to be divided into 2 piles...
421
422         -> (FloatBinds, -- Defns  with level strictly < partition level,
423             FloatBinds) -- The rest
424
425
426 partitionByMajorLevel ctxt_lvl defns
427   = partition float_further defns
428   where
429         -- Float it if we escape a value lambda, or if we get to the top level
430     float_further (my_lvl, _) = my_lvl `ltMajLvl` ctxt_lvl || isTopLvl my_lvl
431         -- The isTopLvl part says that if we can get to the top level, say "yes" anyway
432         -- This means that 
433         --      x = f e
434         -- transforms to 
435         --    lvl = e
436         --    x = f lvl
437         -- which is as it should be
438
439 partitionByLevel ctxt_lvl defns
440   = partition float_further defns
441   where
442     float_further (my_lvl, _) = my_lvl `ltLvl` ctxt_lvl
443 \end{code}
444
445 \begin{code}
446 floatsToBinds :: FloatBinds -> [CoreBind]
447 floatsToBinds floats = map snd floats
448
449 floatsToBindPairs :: FloatBinds -> [(Id,CoreExpr)]
450
451 floatsToBindPairs floats = concat (map mk_pairs floats)
452   where
453    mk_pairs (_, Rec pairs)         = pairs
454    mk_pairs (_, NonRec binder rhs) = [(binder,rhs)]
455
456 install :: FloatBinds -> CoreExpr -> CoreExpr
457
458 install defn_groups expr
459   = foldr install_group expr defn_groups
460   where
461     install_group (_, defns) body = Let defns body
462 \end{code}