Wibbles to the inline-in-InlineRule stuff
[ghc-hetmet.git] / compiler / simplCore / SimplUtils.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[SimplUtils]{The simplifier utilities}
5
6 \begin{code}
7 module SimplUtils (
8         -- Rebuilding
9         mkLam, mkCase, prepareAlts, bindCaseBndr,
10
11         -- Inlining,
12         preInlineUnconditionally, postInlineUnconditionally, 
13         activeInline, activeRule, 
14         simplEnvForGHCi, simplEnvForRules, updModeForInlineRules,
15
16         -- The continuation type
17         SimplCont(..), DupFlag(..), ArgInfo(..),
18         contIsDupable, contResultType, contIsTrivial, contArgs, dropArgs, 
19         countValArgs, countArgs, 
20         mkBoringStop, mkRhsStop, mkLazyArgStop, contIsRhsOrArg,
21         interestingCallContext, 
22
23         interestingArg, mkArgInfo,
24         
25         abstractFloats
26     ) where
27
28 #include "HsVersions.h"
29
30 import SimplEnv
31 import DynFlags
32 import StaticFlags
33 import CoreSyn
34 import qualified CoreSubst
35 import PprCore
36 import CoreFVs
37 import CoreUtils
38 import CoreArity        ( etaExpand, exprEtaExpandArity )
39 import CoreUnfold
40 import Name
41 import Id
42 import Var      ( isCoVar )
43 import NewDemand
44 import SimplMonad
45 import Type     hiding( substTy )
46 import Coercion ( coercionKind )
47 import TyCon
48 import Unify    ( dataConCannotMatch )
49 import VarSet
50 import BasicTypes
51 import Util
52 import MonadUtils
53 import Outputable
54 import FastString
55
56 import Data.List
57 \end{code}
58
59
60 %************************************************************************
61 %*                                                                      *
62                 The SimplCont type
63 %*                                                                      *
64 %************************************************************************
65
66 A SimplCont allows the simplifier to traverse the expression in a 
67 zipper-like fashion.  The SimplCont represents the rest of the expression,
68 "above" the point of interest.
69
70 You can also think of a SimplCont as an "evaluation context", using
71 that term in the way it is used for operational semantics. This is the
72 way I usually think of it, For example you'll often see a syntax for
73 evaluation context looking like
74         C ::= []  |  C e   |  case C of alts  |  C `cast` co
75 That's the kind of thing we are doing here, and I use that syntax in
76 the comments.
77
78
79 Key points:
80   * A SimplCont describes a *strict* context (just like 
81     evaluation contexts do).  E.g. Just [] is not a SimplCont
82
83   * A SimplCont describes a context that *does not* bind
84     any variables.  E.g. \x. [] is not a SimplCont
85
86 \begin{code}
87 data SimplCont  
88   = Stop                -- An empty context, or hole, []     
89         CallCtxt        -- True <=> There is something interesting about
90                         --          the context, and hence the inliner
91                         --          should be a bit keener (see interestingCallContext)
92                         -- Specifically:
93                         --     This is an argument of a function that has RULES
94                         --     Inlining the call might allow the rule to fire
95
96   | CoerceIt            -- C `cast` co
97         OutCoercion             -- The coercion simplified
98         SimplCont
99
100   | ApplyTo             -- C arg
101         DupFlag 
102         InExpr SimplEnv         -- The argument and its static env
103         SimplCont
104
105   | Select              -- case C of alts
106         DupFlag 
107         InId [InAlt] SimplEnv   -- The case binder, alts, and subst-env
108         SimplCont
109
110   -- The two strict forms have no DupFlag, because we never duplicate them
111   | StrictBind          -- (\x* \xs. e) C
112         InId [InBndr]           -- let x* = [] in e     
113         InExpr SimplEnv         --      is a special case 
114         SimplCont       
115
116   | StrictArg           -- e C
117         OutExpr                 -- e; *always* of form (Var v `App1` e1 .. `App` en)
118         CallCtxt                -- Whether *this* argument position is interesting
119         ArgInfo                 -- Whether the function at the head of e has rules, etc
120         SimplCont               --     plus strictness flags for *further* args
121
122 data ArgInfo 
123   = ArgInfo {
124         ai_rules :: Bool,       -- Function has rules (recursively)
125                                 --      => be keener to inline in all args
126         ai_strs :: [Bool],      -- Strictness of arguments
127                                 --   Usually infinite, but if it is finite it guarantees
128                                 --   that the function diverges after being given
129                                 --   that number of args
130         ai_discs :: [Int]       -- Discounts for arguments; non-zero => be keener to inline
131                                 --   Always infinite
132     }
133
134 instance Outputable SimplCont where
135   ppr (Stop interesting)             = ptext (sLit "Stop") <> brackets (ppr interesting)
136   ppr (ApplyTo dup arg _ cont)       = ((ptext (sLit "ApplyTo") <+> ppr dup <+> pprParendExpr arg)
137                                           {-  $$ nest 2 (pprSimplEnv se) -}) $$ ppr cont
138   ppr (StrictBind b _ _ _ cont)      = (ptext (sLit "StrictBind") <+> ppr b) $$ ppr cont
139   ppr (StrictArg f _ _ cont)         = (ptext (sLit "StrictArg") <+> ppr f) $$ ppr cont
140   ppr (Select dup bndr alts _ cont)  = (ptext (sLit "Select") <+> ppr dup <+> ppr bndr) $$ 
141                                        (nest 4 (ppr alts)) $$ ppr cont 
142   ppr (CoerceIt co cont)             = (ptext (sLit "CoerceIt") <+> ppr co) $$ ppr cont
143
144 data DupFlag = OkToDup | NoDup
145
146 instance Outputable DupFlag where
147   ppr OkToDup = ptext (sLit "ok")
148   ppr NoDup   = ptext (sLit "nodup")
149
150
151
152 -------------------
153 mkBoringStop :: SimplCont
154 mkBoringStop = Stop BoringCtxt
155
156 mkRhsStop :: SimplCont  -- See Note [RHS of lets] in CoreUnfold
157 mkRhsStop = Stop (ArgCtxt False)
158
159 mkLazyArgStop :: CallCtxt -> SimplCont
160 mkLazyArgStop cci = Stop cci
161
162 -------------------
163 contIsRhsOrArg :: SimplCont -> Bool
164 contIsRhsOrArg (Stop {})       = True
165 contIsRhsOrArg (StrictBind {}) = True
166 contIsRhsOrArg (StrictArg {})  = True
167 contIsRhsOrArg _               = False
168
169 -------------------
170 contIsDupable :: SimplCont -> Bool
171 contIsDupable (Stop {})                  = True
172 contIsDupable (ApplyTo  OkToDup _ _ _)   = True
173 contIsDupable (Select   OkToDup _ _ _ _) = True
174 contIsDupable (CoerceIt _ cont)          = contIsDupable cont
175 contIsDupable _                          = False
176
177 -------------------
178 contIsTrivial :: SimplCont -> Bool
179 contIsTrivial (Stop {})                   = True
180 contIsTrivial (ApplyTo _ (Type _) _ cont) = contIsTrivial cont
181 contIsTrivial (CoerceIt _ cont)           = contIsTrivial cont
182 contIsTrivial _                           = False
183
184 -------------------
185 contResultType :: SimplEnv -> OutType -> SimplCont -> OutType
186 contResultType env ty cont
187   = go cont ty
188   where
189     subst_ty se ty = substTy (se `setInScope` env) ty
190
191     go (Stop {})                      ty = ty
192     go (CoerceIt co cont)             _  = go cont (snd (coercionKind co))
193     go (StrictBind _ bs body se cont) _  = go cont (subst_ty se (exprType (mkLams bs body)))
194     go (StrictArg fn _ _ cont)        _  = go cont (funResultTy (exprType fn))
195     go (Select _ _ alts se cont)      _  = go cont (subst_ty se (coreAltsType alts))
196     go (ApplyTo _ arg se cont)        ty = go cont (apply_to_arg ty arg se)
197
198     apply_to_arg ty (Type ty_arg) se = applyTy ty (subst_ty se ty_arg)
199     apply_to_arg ty _             _  = funResultTy ty
200
201 -------------------
202 countValArgs :: SimplCont -> Int
203 countValArgs (ApplyTo _ (Type _) _ cont) = countValArgs cont
204 countValArgs (ApplyTo _ _        _ cont) = 1 + countValArgs cont
205 countValArgs _                           = 0
206
207 countArgs :: SimplCont -> Int
208 countArgs (ApplyTo _ _ _ cont) = 1 + countArgs cont
209 countArgs _                    = 0
210
211 contArgs :: SimplCont -> ([OutExpr], SimplCont)
212 -- Uses substitution to turn each arg into an OutExpr
213 contArgs cont = go [] cont
214   where
215     go args (ApplyTo _ arg se cont) = go (substExpr se arg : args) cont
216     go args cont                    = (reverse args, cont)
217
218 dropArgs :: Int -> SimplCont -> SimplCont
219 dropArgs 0 cont = cont
220 dropArgs n (ApplyTo _ _ _ cont) = dropArgs (n-1) cont
221 dropArgs n other                = pprPanic "dropArgs" (ppr n <+> ppr other)
222 \end{code}
223
224
225 Note [Interesting call context]
226 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
227 We want to avoid inlining an expression where there can't possibly be
228 any gain, such as in an argument position.  Hence, if the continuation
229 is interesting (eg. a case scrutinee, application etc.) then we
230 inline, otherwise we don't.  
231
232 Previously some_benefit used to return True only if the variable was
233 applied to some value arguments.  This didn't work:
234
235         let x = _coerce_ (T Int) Int (I# 3) in
236         case _coerce_ Int (T Int) x of
237                 I# y -> ....
238
239 we want to inline x, but can't see that it's a constructor in a case
240 scrutinee position, and some_benefit is False.
241
242 Another example:
243
244 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
245
246 ....  case dMonadST _@_ x0 of (a,b,c) -> ....
247
248 we'd really like to inline dMonadST here, but we *don't* want to
249 inline if the case expression is just
250
251         case x of y { DEFAULT -> ... }
252
253 since we can just eliminate this case instead (x is in WHNF).  Similar
254 applies when x is bound to a lambda expression.  Hence
255 contIsInteresting looks for case expressions with just a single
256 default case.
257
258
259 \begin{code}
260 interestingCallContext :: SimplCont -> CallCtxt
261 -- See Note [Interesting call context]
262 interestingCallContext cont
263   = interesting cont
264   where
265     interesting (Select _ bndr _ _ _)
266         | isDeadBinder bndr = CaseCtxt
267         | otherwise         = ArgCtxt False     -- If the binder is used, this
268                                                 -- is like a strict let
269                                                 -- See Note [RHS of lets] in CoreUnfold
270                 
271     interesting (ApplyTo _ arg _ cont)
272         | isTypeArg arg = interesting cont
273         | otherwise     = ValAppCtxt    -- Can happen if we have (f Int |> co) y
274                                         -- If f has an INLINE prag we need to give it some
275                                         -- motivation to inline. See Note [Cast then apply]
276                                         -- in CoreUnfold
277
278     interesting (StrictArg _ cci _ _)   = cci
279     interesting (StrictBind {})         = BoringCtxt
280     interesting (Stop cci)              = cci
281     interesting (CoerceIt _ cont)       = interesting cont
282         -- If this call is the arg of a strict function, the context
283         -- is a bit interesting.  If we inline here, we may get useful
284         -- evaluation information to avoid repeated evals: e.g.
285         --      x + (y * z)
286         -- Here the contIsInteresting makes the '*' keener to inline,
287         -- which in turn exposes a constructor which makes the '+' inline.
288         -- Assuming that +,* aren't small enough to inline regardless.
289         --
290         -- It's also very important to inline in a strict context for things
291         -- like
292         --              foldr k z (f x)
293         -- Here, the context of (f x) is strict, and if f's unfolding is
294         -- a build it's *great* to inline it here.  So we must ensure that
295         -- the context for (f x) is not totally uninteresting.
296
297
298 -------------------
299 mkArgInfo :: Id
300           -> [CoreRule] -- Rules for function
301           -> Int        -- Number of value args
302           -> SimplCont  -- Context of the call
303           -> ArgInfo
304
305 mkArgInfo fun rules n_val_args call_cont
306   | n_val_args < idArity fun            -- Note [Unsaturated functions]
307   = ArgInfo { ai_rules = False
308             , ai_strs = vanilla_stricts 
309             , ai_discs = vanilla_discounts }
310   | otherwise
311   = ArgInfo { ai_rules = interestingArgContext rules call_cont
312             , ai_strs  = add_type_str (idType fun) arg_stricts
313             , ai_discs = arg_discounts }
314   where
315     vanilla_discounts, arg_discounts :: [Int]
316     vanilla_discounts = repeat 0
317     arg_discounts = case idUnfolding fun of
318                         CoreUnfolding {uf_guidance = UnfoldIfGoodArgs {ug_args = discounts}}
319                               -> discounts ++ vanilla_discounts
320                         _     -> vanilla_discounts
321
322     vanilla_stricts, arg_stricts :: [Bool]
323     vanilla_stricts  = repeat False
324
325     arg_stricts
326       = case splitStrictSig (idNewStrictness fun) of
327           (demands, result_info)
328                 | not (demands `lengthExceeds` n_val_args)
329                 ->      -- Enough args, use the strictness given.
330                         -- For bottoming functions we used to pretend that the arg
331                         -- is lazy, so that we don't treat the arg as an
332                         -- interesting context.  This avoids substituting
333                         -- top-level bindings for (say) strings into 
334                         -- calls to error.  But now we are more careful about
335                         -- inlining lone variables, so its ok (see SimplUtils.analyseCont)
336                    if isBotRes result_info then
337                         map isStrictDmd demands         -- Finite => result is bottom
338                    else
339                         map isStrictDmd demands ++ vanilla_stricts
340                | otherwise
341                -> WARN( True, text "More demands than arity" <+> ppr fun <+> ppr (idArity fun) 
342                                 <+> ppr n_val_args <+> ppr demands ) 
343                    vanilla_stricts      -- Not enough args, or no strictness
344
345     add_type_str :: Type -> [Bool] -> [Bool]
346     -- If the function arg types are strict, record that in the 'strictness bits'
347     -- No need to instantiate because unboxed types (which dominate the strict
348     -- types) can't instantiate type variables.
349     -- add_type_str is done repeatedly (for each call); might be better 
350     -- once-for-all in the function
351     -- But beware primops/datacons with no strictness
352     add_type_str _ [] = []
353     add_type_str fun_ty strs            -- Look through foralls
354         | Just (_, fun_ty') <- splitForAllTy_maybe fun_ty       -- Includes coercions
355         = add_type_str fun_ty' strs
356     add_type_str fun_ty (str:strs)      -- Add strict-type info
357         | Just (arg_ty, fun_ty') <- splitFunTy_maybe fun_ty
358         = (str || isStrictType arg_ty) : add_type_str fun_ty' strs
359     add_type_str _ strs
360         = strs
361
362 {- Note [Unsaturated functions]
363   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
364 Consider (test eyeball/inline4)
365         x = a:as
366         y = f x
367 where f has arity 2.  Then we do not want to inline 'x', because
368 it'll just be floated out again.  Even if f has lots of discounts
369 on its first argument -- it must be saturated for these to kick in
370 -}
371
372 interestingArgContext :: [CoreRule] -> SimplCont -> Bool
373 -- If the argument has form (f x y), where x,y are boring,
374 -- and f is marked INLINE, then we don't want to inline f.
375 -- But if the context of the argument is
376 --      g (f x y) 
377 -- where g has rules, then we *do* want to inline f, in case it
378 -- exposes a rule that might fire.  Similarly, if the context is
379 --      h (g (f x x))
380 -- where h has rules, then we do want to inline f; hence the
381 -- call_cont argument to interestingArgContext
382 --
383 -- The ai-rules flag makes this happen; if it's
384 -- set, the inliner gets just enough keener to inline f 
385 -- regardless of how boring f's arguments are, if it's marked INLINE
386 --
387 -- The alternative would be to *always* inline an INLINE function,
388 -- regardless of how boring its context is; but that seems overkill
389 -- For example, it'd mean that wrapper functions were always inlined
390 interestingArgContext rules call_cont
391   = notNull rules || enclosing_fn_has_rules
392   where
393     enclosing_fn_has_rules = go call_cont
394
395     go (Select {})           = False
396     go (ApplyTo {})          = False
397     go (StrictArg _ cci _ _) = interesting cci
398     go (StrictBind {})       = False    -- ??
399     go (CoerceIt _ c)        = go c
400     go (Stop cci)            = interesting cci
401
402     interesting (ArgCtxt rules) = rules
403     interesting _               = False
404 \end{code}
405
406
407
408 %************************************************************************
409 %*                                                                      *
410 \subsection{Decisions about inlining}
411 %*                                                                      *
412 %************************************************************************
413
414 \begin{code}
415 simplEnvForGHCi :: SimplEnv
416 simplEnvForGHCi = mkSimplEnv allOffSwitchChecker $
417                   SimplGently { sm_rules = False, sm_inline = False }
418    -- Do not do any inlining, in case we expose some unboxed
419    -- tuple stuff that confuses the bytecode interpreter
420
421 simplEnvForRules :: SimplEnv
422 simplEnvForRules = mkSimplEnv allOffSwitchChecker $
423                    SimplGently { sm_rules = True, sm_inline = False }
424
425 updModeForInlineRules :: SimplifierMode -> SimplifierMode
426 updModeForInlineRules mode
427   = case mode of      
428       SimplGently {} -> mode    -- Don't modify mode if we already gentle
429       SimplPhase  {} -> SimplGently { sm_rules = True, sm_inline = True }
430         -- Simplify as much as possible, subject to the usual "gentle" rules
431 \end{code}
432
433 Inlining is controlled partly by the SimplifierMode switch.  This has two
434 settings
435         
436         SimplGently     (a) Simplifying before specialiser/full laziness
437                         (b) Simplifiying inside InlineRules
438                         (c) Simplifying the LHS of a rule
439                         (d) Simplifying a GHCi expression or Template 
440                                 Haskell splice
441
442         SimplPhase n _   Used at all other times
443
444 Note [Gentle mode]
445 ~~~~~~~~~~~~~~~~~~
446 Gentle mode has a separate boolean flag to control
447         a) inlining (sm_inline flag)
448         b) rules    (sm_rules  flag)
449 A key invariant about Gentle mode is that it is treated as the EARLIEST
450 phase.  Something is inlined if the sm_inline flag is on AND the thing
451 is inlinable in the earliest phase.  This is important. Example
452
453   {-# INLINE [~1] g #-}
454   g = ...
455   
456   {-# INLINE f #-}
457   f x = g (g x)
458
459 If we were to inline g into f's inlining, then an importing module would
460 never be able to do
461         f e --> g (g e) ---> RULE fires
462 because the InlineRule for f has had g inlined into it.
463
464 On the other hand, it is bad not to do ANY inlining into an
465 InlineRule, because then recursive knots in instance declarations
466 don't get unravelled.
467
468 However, *sometimes* SimplGently must do no call-site inlining at all.
469 Before full laziness we must be careful not to inline wrappers,
470 because doing so inhibits floating
471     e.g. ...(case f x of ...)...
472     ==> ...(case (case x of I# x# -> fw x#) of ...)...
473     ==> ...(case x of I# x# -> case fw x# of ...)...
474 and now the redex (f x) isn't floatable any more.
475
476 The no-inlining thing is also important for Template Haskell.  You might be 
477 compiling in one-shot mode with -O2; but when TH compiles a splice before
478 running it, we don't want to use -O2.  Indeed, we don't want to inline
479 anything, because the byte-code interpreter might get confused about 
480 unboxed tuples and suchlike.
481
482 Note [RULEs enabled in SimplGently]
483 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
484 RULES are enabled when doing "gentle" simplification.  Two reasons:
485
486   * We really want the class-op cancellation to happen:
487         op (df d1 d2) --> $cop3 d1 d2
488     because this breaks the mutual recursion between 'op' and 'df'
489
490   * I wanted the RULE
491         lift String ===> ...
492     to work in Template Haskell when simplifying
493     splices, so we get simpler code for literal strings
494
495 Note [Simplifying gently inside InlineRules]
496 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
497 We don't do much simplification inside InlineRules (which come from
498 INLINE pragmas).  It really is important to switch off inlinings
499 inside such expressions.  Consider the following example
500
501         let f = \pq -> BIG
502         in
503         let g = \y -> f y y
504             {-# INLINE g #-}
505         in ...g...g...g...g...g...
506
507 Now, if that's the ONLY occurrence of f, it will be inlined inside g,
508 and thence copied multiple times when g is inlined.  
509
510 This function may be inlinined in other modules, so we don't want to
511 remove (by inlining) calls to functions that have specialisations, or
512 that may have transformation rules in an importing scope.
513
514 E.g.    {-# INLINE f #-}
515         f x = ...g...
516
517 and suppose that g is strict *and* has specialisations.  If we inline
518 g's wrapper, we deny f the chance of getting the specialised version
519 of g when f is inlined at some call site (perhaps in some other
520 module).
521
522 It's also important not to inline a worker back into a wrapper.
523 A wrapper looks like
524         wraper = inline_me (\x -> ...worker... )
525 Normally, the inline_me prevents the worker getting inlined into
526 the wrapper (initially, the worker's only call site!).  But,
527 if the wrapper is sure to be called, the strictness analyser will
528 mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
529 continuation.  That's why the keep_inline predicate returns True for
530 ArgOf continuations.  It shouldn't do any harm not to dissolve the
531 inline-me note under these circumstances.
532
533 Although we do very little simplification inside an InlineRule,
534 the RHS is simplified as normal.  For example:
535
536         all xs = foldr (&&) True xs
537         any p = all . map p  {-# INLINE any #-}
538
539 The RHS of 'any' will get optimised and deforested; but the InlineRule
540 will still mention the original RHS.
541
542
543 preInlineUnconditionally
544 ~~~~~~~~~~~~~~~~~~~~~~~~
545 @preInlineUnconditionally@ examines a bndr to see if it is used just
546 once in a completely safe way, so that it is safe to discard the
547 binding inline its RHS at the (unique) usage site, REGARDLESS of how
548 big the RHS might be.  If this is the case we don't simplify the RHS
549 first, but just inline it un-simplified.
550
551 This is much better than first simplifying a perhaps-huge RHS and then
552 inlining and re-simplifying it.  Indeed, it can be at least quadratically
553 better.  Consider
554
555         x1 = e1
556         x2 = e2[x1]
557         x3 = e3[x2]
558         ...etc...
559         xN = eN[xN-1]
560
561 We may end up simplifying e1 N times, e2 N-1 times, e3 N-3 times etc.
562 This can happen with cascades of functions too:
563
564         f1 = \x1.e1
565         f2 = \xs.e2[f1]
566         f3 = \xs.e3[f3]
567         ...etc...
568
569 THE MAIN INVARIANT is this:
570
571         ----  preInlineUnconditionally invariant -----
572    IF preInlineUnconditionally chooses to inline x = <rhs>
573    THEN doing the inlining should not change the occurrence
574         info for the free vars of <rhs>
575         ----------------------------------------------
576
577 For example, it's tempting to look at trivial binding like
578         x = y
579 and inline it unconditionally.  But suppose x is used many times,
580 but this is the unique occurrence of y.  Then inlining x would change
581 y's occurrence info, which breaks the invariant.  It matters: y
582 might have a BIG rhs, which will now be dup'd at every occurrenc of x.
583
584
585 Even RHSs labelled InlineMe aren't caught here, because there might be
586 no benefit from inlining at the call site.
587
588 [Sept 01] Don't unconditionally inline a top-level thing, because that
589 can simply make a static thing into something built dynamically.  E.g.
590         x = (a,b)
591         main = \s -> h x
592
593 [Remember that we treat \s as a one-shot lambda.]  No point in
594 inlining x unless there is something interesting about the call site.
595
596 But watch out: if you aren't careful, some useful foldr/build fusion
597 can be lost (most notably in spectral/hartel/parstof) because the
598 foldr didn't see the build.  Doing the dynamic allocation isn't a big
599 deal, in fact, but losing the fusion can be.  But the right thing here
600 seems to be to do a callSiteInline based on the fact that there is
601 something interesting about the call site (it's strict).  Hmm.  That
602 seems a bit fragile.
603
604 Conclusion: inline top level things gaily until Phase 0 (the last
605 phase), at which point don't.
606
607 Note [pre/postInlineUnconditionally in gentle mode]
608 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
609 Even in gentle mode we want to do preInlineUnconditionally.  The
610 reason is that too little clean-up happens if you don't inline
611 use-once things.  Also a bit of inlining is *good* for full laziness;
612 it can expose constant sub-expressions.  Example in
613 spectral/mandel/Mandel.hs, where the mandelset function gets a useful
614 let-float if you inline windowToViewport
615
616 However, as usual for Gentle mode, do not inline things that are
617 inactive in the intial stages.  See Note [Gentle mode].
618
619 \begin{code}
620 preInlineUnconditionally :: SimplEnv -> TopLevelFlag -> InId -> InExpr -> Bool
621 preInlineUnconditionally env top_lvl bndr rhs
622   | not active             = False
623   | opt_SimplNoPreInlining = False
624   | otherwise = case idOccInfo bndr of
625                   IAmDead                    -> True    -- Happens in ((\x.1) v)
626                   OneOcc in_lam True int_cxt -> try_once in_lam int_cxt
627                   _                          -> False
628   where
629     phase = getMode env
630     active = case phase of
631                    SimplGently {} -> isEarlyActive act
632                         -- See Note [pre/postInlineUnconditionally in gentle mode]
633                    SimplPhase n _ -> isActive n act
634     act = idInlineActivation bndr
635
636     try_once in_lam int_cxt     -- There's one textual occurrence
637         | not in_lam = isNotTopLevel top_lvl || early_phase
638         | otherwise  = int_cxt && canInlineInLam rhs
639
640 -- Be very careful before inlining inside a lambda, becuase (a) we must not 
641 -- invalidate occurrence information, and (b) we want to avoid pushing a
642 -- single allocation (here) into multiple allocations (inside lambda).  
643 -- Inlining a *function* with a single *saturated* call would be ok, mind you.
644 --      || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
645 --      where 
646 --              is_cheap = exprIsCheap rhs
647 --              ok = is_cheap && int_cxt
648
649         --      int_cxt         The context isn't totally boring
650         -- E.g. let f = \ab.BIG in \y. map f xs
651         --      Don't want to substitute for f, because then we allocate
652         --      its closure every time the \y is called
653         -- But: let f = \ab.BIG in \y. map (f y) xs
654         --      Now we do want to substitute for f, even though it's not 
655         --      saturated, because we're going to allocate a closure for 
656         --      (f y) every time round the loop anyhow.
657
658         -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
659         -- so substituting rhs inside a lambda doesn't change the occ info.
660         -- Sadly, not quite the same as exprIsHNF.
661     canInlineInLam (Lit _)              = True
662     canInlineInLam (Lam b e)            = isRuntimeVar b || canInlineInLam e
663     canInlineInLam (Note _ e)           = canInlineInLam e
664     canInlineInLam _                    = False
665
666     early_phase = case phase of
667                         SimplPhase 0 _ -> False
668                         _              -> True
669 -- If we don't have this early_phase test, consider
670 --      x = length [1,2,3]
671 -- The full laziness pass carefully floats all the cons cells to
672 -- top level, and preInlineUnconditionally floats them all back in.
673 -- Result is (a) static allocation replaced by dynamic allocation
674 --           (b) many simplifier iterations because this tickles
675 --               a related problem; only one inlining per pass
676 -- 
677 -- On the other hand, I have seen cases where top-level fusion is
678 -- lost if we don't inline top level thing (e.g. string constants)
679 -- Hence the test for phase zero (which is the phase for all the final
680 -- simplifications).  Until phase zero we take no special notice of
681 -- top level things, but then we become more leery about inlining
682 -- them.  
683
684 \end{code}
685
686 postInlineUnconditionally
687 ~~~~~~~~~~~~~~~~~~~~~~~~~
688 @postInlineUnconditionally@ decides whether to unconditionally inline
689 a thing based on the form of its RHS; in particular if it has a
690 trivial RHS.  If so, we can inline and discard the binding altogether.
691
692 NB: a loop breaker has must_keep_binding = True and non-loop-breakers
693 only have *forward* references Hence, it's safe to discard the binding
694         
695 NOTE: This isn't our last opportunity to inline.  We're at the binding
696 site right now, and we'll get another opportunity when we get to the
697 ocurrence(s)
698
699 Note that we do this unconditional inlining only for trival RHSs.
700 Don't inline even WHNFs inside lambdas; doing so may simply increase
701 allocation when the function is called. This isn't the last chance; see
702 NOTE above.
703
704 NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here Why?
705 Because we don't even want to inline them into the RHS of constructor
706 arguments. See NOTE above
707
708 NB: At one time even NOINLINE was ignored here: if the rhs is trivial
709 it's best to inline it anyway.  We often get a=E; b=a from desugaring,
710 with both a and b marked NOINLINE.  But that seems incompatible with
711 our new view that inlining is like a RULE, so I'm sticking to the 'active'
712 story for now.
713
714 \begin{code}
715 postInlineUnconditionally 
716     :: SimplEnv -> TopLevelFlag
717     -> OutId            -- The binder (an InId would be fine too)
718     -> OccInfo          -- From the InId
719     -> OutExpr
720     -> Unfolding
721     -> Bool
722 postInlineUnconditionally env top_lvl bndr occ_info rhs unfolding
723   | not active             = False
724   | isLoopBreaker occ_info = False      -- If it's a loop-breaker of any kind, don't inline
725                                         -- because it might be referred to "earlier"
726   | isExportedId bndr      = False
727   | isInlineRule unfolding = False      -- Note [InlineRule and postInlineUnconditionally]
728   | exprIsTrivial rhs      = True
729   | otherwise
730   = case occ_info of
731         -- The point of examining occ_info here is that for *non-values* 
732         -- that occur outside a lambda, the call-site inliner won't have
733         -- a chance (becuase it doesn't know that the thing
734         -- only occurs once).   The pre-inliner won't have gotten
735         -- it either, if the thing occurs in more than one branch
736         -- So the main target is things like
737         --      let x = f y in
738         --      case v of
739         --         True  -> case x of ...
740         --         False -> case x of ...
741         -- I'm not sure how important this is in practice
742       OneOcc in_lam _one_br int_cxt     -- OneOcc => no code-duplication issue
743         ->     smallEnoughToInline unfolding    -- Small enough to dup
744                         -- ToDo: consider discount on smallEnoughToInline if int_cxt is true
745                         --
746                         -- NB: Do NOT inline arbitrarily big things, even if one_br is True
747                         -- Reason: doing so risks exponential behaviour.  We simplify a big
748                         --         expression, inline it, and simplify it again.  But if the
749                         --         very same thing happens in the big expression, we get 
750                         --         exponential cost!
751                         -- PRINCIPLE: when we've already simplified an expression once, 
752                         -- make sure that we only inline it if it's reasonably small.
753
754            &&  ((isNotTopLevel top_lvl && not in_lam) || 
755                         -- But outside a lambda, we want to be reasonably aggressive
756                         -- about inlining into multiple branches of case
757                         -- e.g. let x = <non-value> 
758                         --      in case y of { C1 -> ..x..; C2 -> ..x..; C3 -> ... } 
759                         -- Inlining can be a big win if C3 is the hot-spot, even if
760                         -- the uses in C1, C2 are not 'interesting'
761                         -- An example that gets worse if you add int_cxt here is 'clausify'
762
763                 (isCheapUnfolding unfolding && int_cxt))
764                         -- isCheap => acceptable work duplication; in_lam may be true
765                         -- int_cxt to prevent us inlining inside a lambda without some 
766                         -- good reason.  See the notes on int_cxt in preInlineUnconditionally
767
768       IAmDead -> True   -- This happens; for example, the case_bndr during case of
769                         -- known constructor:  case (a,b) of x { (p,q) -> ... }
770                         -- Here x isn't mentioned in the RHS, so we don't want to
771                         -- create the (dead) let-binding  let x = (a,b) in ...
772
773       _ -> False
774
775 -- Here's an example that we don't handle well:
776 --      let f = if b then Left (\x.BIG) else Right (\y.BIG)
777 --      in \y. ....case f of {...} ....
778 -- Here f is used just once, and duplicating the case work is fine (exprIsCheap).
779 -- But
780 --  - We can't preInlineUnconditionally because that woud invalidate
781 --    the occ info for b.
782 --  - We can't postInlineUnconditionally because the RHS is big, and
783 --    that risks exponential behaviour
784 --  - We can't call-site inline, because the rhs is big
785 -- Alas!
786
787   where
788     active = case getMode env of
789                    SimplGently {} -> isEarlyActive act
790                         -- See Note [pre/postInlineUnconditionally in gentle mode]
791                    SimplPhase n _ -> isActive n act
792     act = idInlineActivation bndr
793
794 activeInline :: SimplEnv -> OutId -> Bool
795 activeInline env id
796   | isNonRuleLoopBreaker (idOccInfo id)   -- Things with an INLINE pragma may have 
797                                           -- an unfolding *and* be a loop breaker
798   = False                                 -- (maybe the knot is not yet untied)
799   | otherwise
800   = case getMode env of
801       SimplGently { sm_inline = inlining_on } 
802          -> inlining_on && isEarlyActive act
803         -- See Note [Gentle mode]
804
805         -- NB: we used to have a second exception, for data con wrappers.
806         -- On the grounds that we use gentle mode for rule LHSs, and 
807         -- they match better when data con wrappers are inlined.
808         -- But that only really applies to the trivial wrappers (like (:)),
809         -- and they are now constructed as Compulsory unfoldings (in MkId)
810         -- so they'll happen anyway.
811
812       SimplPhase n _ -> isActive n act
813   where
814     act = idInlineActivation id
815
816 activeRule :: DynFlags -> SimplEnv -> Maybe (Activation -> Bool)
817 -- Nothing => No rules at all
818 activeRule dflags env
819   | not (dopt Opt_EnableRewriteRules dflags)
820   = Nothing     -- Rewriting is off
821   | otherwise
822   = case getMode env of
823       SimplGently { sm_rules = rules_on } 
824         | rules_on  -> Just isEarlyActive       -- Note [RULEs enabled in SimplGently]
825         | otherwise -> Nothing
826       SimplPhase n _ -> Just (isActive n)
827 \end{code}
828
829 Note [InlineRule and postInlineUnconditionally]
830 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
831 Do not do postInlineUnconditionally if the Id has an InlineRule, otherwise
832 we lose the unfolding.  Example
833
834      -- f has InlineRule with rhs (e |> co)
835      --   where 'e' is big
836      f = e |> co
837
838 Then there's a danger we'll optimise to
839
840      f' = e
841      f = f' |> co
842
843 and now postInlineUnconditionally, losing the InlineRule on f.  Now f'
844 won't inline because 'e' is too big.
845
846
847 %************************************************************************
848 %*                                                                      *
849         Rebuilding a lambda
850 %*                                                                      *
851 %************************************************************************
852
853 \begin{code}
854 mkLam :: SimplEnv -> [OutBndr] -> OutExpr -> SimplM OutExpr
855 -- mkLam tries three things
856 --      a) eta reduction, if that gives a trivial expression
857 --      b) eta expansion [only if there are some value lambdas]
858
859 mkLam _b [] body 
860   = return body
861 mkLam env bndrs body
862   = do  { dflags <- getDOptsSmpl
863         ; mkLam' dflags bndrs body }
864   where
865     mkLam' :: DynFlags -> [OutBndr] -> OutExpr -> SimplM OutExpr
866     mkLam' dflags bndrs (Cast body co)
867       | not (any bad bndrs)
868         -- Note [Casts and lambdas]
869       = do { lam <- mkLam' dflags bndrs body
870            ; return (mkCoerce (mkPiTypes bndrs co) lam) }
871       where
872         co_vars  = tyVarsOfType co
873         bad bndr = isCoVar bndr && bndr `elemVarSet` co_vars      
874
875     mkLam' dflags bndrs body
876       | dopt Opt_DoEtaReduction dflags,
877         Just etad_lam <- tryEtaReduce bndrs body
878       = do { tick (EtaReduction (head bndrs))
879            ; return etad_lam }
880
881       | dopt Opt_DoLambdaEtaExpansion dflags,
882         not (inGentleMode env),       -- In gentle mode don't eta-expansion
883         any isRuntimeVar bndrs        -- because it can clutter up the code
884                                       -- with casts etc that may not be removed
885       = do { let body' = tryEtaExpansion dflags body
886            ; return (mkLams bndrs body') }
887    
888       | otherwise 
889       = return (mkLams bndrs body)
890 \end{code}
891
892 Note [Casts and lambdas]
893 ~~~~~~~~~~~~~~~~~~~~~~~~
894 Consider 
895         (\x. (\y. e) `cast` g1) `cast` g2
896 There is a danger here that the two lambdas look separated, and the 
897 full laziness pass might float an expression to between the two.
898
899 So this equation in mkLam' floats the g1 out, thus:
900         (\x. e `cast` g1)  -->  (\x.e) `cast` (tx -> g1)
901 where x:tx.
902
903 In general, this floats casts outside lambdas, where (I hope) they
904 might meet and cancel with some other cast:
905         \x. e `cast` co   ===>   (\x. e) `cast` (tx -> co)
906         /\a. e `cast` co  ===>   (/\a. e) `cast` (/\a. co)
907         /\g. e `cast` co  ===>   (/\g. e) `cast` (/\g. co)
908                           (if not (g `in` co))
909
910 Notice that it works regardless of 'e'.  Originally it worked only
911 if 'e' was itself a lambda, but in some cases that resulted in 
912 fruitless iteration in the simplifier.  A good example was when
913 compiling Text.ParserCombinators.ReadPrec, where we had a definition 
914 like    (\x. Get `cast` g)
915 where Get is a constructor with nonzero arity.  Then mkLam eta-expanded
916 the Get, and the next iteration eta-reduced it, and then eta-expanded 
917 it again.
918
919 Note also the side condition for the case of coercion binders.
920 It does not make sense to transform
921         /\g. e `cast` g  ==>  (/\g.e) `cast` (/\g.g)
922 because the latter is not well-kinded.
923
924 --      c) floating lets out through big lambdas 
925 --              [only if all tyvar lambdas, and only if this lambda
926 --               is the RHS of a let]
927
928 {-      Sept 01: I'm experimenting with getting the
929         full laziness pass to float out past big lambdsa
930  | all isTyVar bndrs,   -- Only for big lambdas
931    contIsRhs cont       -- Only try the rhs type-lambda floating
932                         -- if this is indeed a right-hand side; otherwise
933                         -- we end up floating the thing out, only for float-in
934                         -- to float it right back in again!
935  = do (floats, body') <- tryRhsTyLam env bndrs body
936       return (floats, mkLams bndrs body')
937 -}
938
939
940 %************************************************************************
941 %*                                                                      *
942                 Eta reduction
943 %*                                                                      *
944 %************************************************************************
945
946 Note [Eta reduction conditions]
947 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
948 We try for eta reduction here, but *only* if we get all the way to an
949 trivial expression.  We don't want to remove extra lambdas unless we
950 are going to avoid allocating this thing altogether.
951
952 There are some particularly delicate points here:
953
954 * Eta reduction is not valid in general:  
955         \x. bot  /=  bot
956   This matters, partly for old-fashioned correctness reasons but,
957   worse, getting it wrong can yield a seg fault. Consider
958         f = \x.f x
959         h y = case (case y of { True -> f `seq` True; False -> False }) of
960                 True -> ...; False -> ...
961
962   If we (unsoundly) eta-reduce f to get f=f, the strictness analyser
963   says f=bottom, and replaces the (f `seq` True) with just
964   (f `cast` unsafe-co).  BUT, as thing stand, 'f' got arity 1, and it
965   *keeps* arity 1 (perhaps also wrongly).  So CorePrep eta-expands 
966   the definition again, so that it does not termninate after all.
967   Result: seg-fault because the boolean case actually gets a function value.
968   See Trac #1947.
969
970   So it's important to to the right thing.
971
972 * Note [Arity care]: we need to be careful if we just look at f's
973   arity. Currently (Dec07), f's arity is visible in its own RHS (see
974   Note [Arity robustness] in SimplEnv) so we must *not* trust the
975   arity when checking that 'f' is a value.  Otherwise we will
976   eta-reduce
977       f = \x. f x
978   to
979       f = f
980   Which might change a terminiating program (think (f `seq` e)) to a 
981   non-terminating one.  So we check for being a loop breaker first.
982
983   However for GlobalIds we can look at the arity; and for primops we
984   must, since they have no unfolding.  
985
986 * Regardless of whether 'f' is a value, we always want to 
987   reduce (/\a -> f a) to f
988   This came up in a RULE: foldr (build (/\a -> g a))
989   did not match           foldr (build (/\b -> ...something complex...))
990   The type checker can insert these eta-expanded versions,
991   with both type and dictionary lambdas; hence the slightly 
992   ad-hoc isDictId
993
994 * Never *reduce* arity. For example
995       f = \xy. g x y
996   Then if h has arity 1 we don't want to eta-reduce because then
997   f's arity would decrease, and that is bad
998
999 These delicacies are why we don't use exprIsTrivial and exprIsHNF here.
1000 Alas.
1001
1002 \begin{code}
1003 tryEtaReduce :: [OutBndr] -> OutExpr -> Maybe OutExpr
1004 tryEtaReduce bndrs body 
1005   = go (reverse bndrs) body
1006   where
1007     incoming_arity = count isId bndrs
1008
1009     go (b : bs) (App fun arg) | ok_arg b arg = go bs fun        -- Loop round
1010     go []       fun           | ok_fun fun   = Just fun         -- Success!
1011     go _        _                            = Nothing          -- Failure!
1012
1013         -- Note [Eta reduction conditions]
1014     ok_fun (App fun (Type ty)) 
1015         | not (any (`elemVarSet` tyVarsOfType ty) bndrs)
1016         =  ok_fun fun
1017     ok_fun (Var fun_id)
1018         =  not (fun_id `elem` bndrs)
1019         && (ok_fun_id fun_id || all ok_lam bndrs)
1020     ok_fun _fun = False
1021
1022     ok_fun_id fun = fun_arity fun >= incoming_arity
1023
1024     fun_arity fun             -- See Note [Arity care]
1025        | isLocalId fun && isLoopBreaker (idOccInfo fun) = 0
1026        | otherwise = idArity fun              
1027
1028     ok_lam v = isTyVar v || isDictId v
1029
1030     ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
1031 \end{code}
1032
1033
1034 %************************************************************************
1035 %*                                                                      *
1036                 Eta expansion
1037 %*                                                                      *
1038 %************************************************************************
1039
1040
1041 We go for:
1042    f = \x1..xn -> N  ==>   f = \x1..xn y1..ym -> N y1..ym
1043                                  (n >= 0)
1044
1045 where (in both cases) 
1046
1047         * The xi can include type variables
1048
1049         * The yi are all value variables
1050
1051         * N is a NORMAL FORM (i.e. no redexes anywhere)
1052           wanting a suitable number of extra args.
1053
1054 The biggest reason for doing this is for cases like
1055
1056         f = \x -> case x of
1057                     True  -> \y -> e1
1058                     False -> \y -> e2
1059
1060 Here we want to get the lambdas together.  A good exmaple is the nofib
1061 program fibheaps, which gets 25% more allocation if you don't do this
1062 eta-expansion.
1063
1064 We may have to sandwich some coerces between the lambdas
1065 to make the types work.   exprEtaExpandArity looks through coerces
1066 when computing arity; and etaExpand adds the coerces as necessary when
1067 actually computing the expansion.
1068
1069 \begin{code}
1070 tryEtaExpansion :: DynFlags -> OutExpr -> OutExpr
1071 -- There is at least one runtime binder in the binders
1072 tryEtaExpansion dflags body
1073   = etaExpand fun_arity body
1074   where
1075     fun_arity = exprEtaExpandArity dflags body
1076 \end{code}
1077
1078
1079 %************************************************************************
1080 %*                                                                      *
1081 \subsection{Floating lets out of big lambdas}
1082 %*                                                                      *
1083 %************************************************************************
1084
1085 Note [Floating and type abstraction]
1086 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1087 Consider this:
1088         x = /\a. C e1 e2
1089 We'd like to float this to 
1090         y1 = /\a. e1
1091         y2 = /\a. e2
1092         x  = /\a. C (y1 a) (y2 a)
1093 for the usual reasons: we want to inline x rather vigorously.
1094
1095 You may think that this kind of thing is rare.  But in some programs it is
1096 common.  For example, if you do closure conversion you might get:
1097
1098         data a :-> b = forall e. (e -> a -> b) :$ e
1099
1100         f_cc :: forall a. a :-> a
1101         f_cc = /\a. (\e. id a) :$ ()
1102
1103 Now we really want to inline that f_cc thing so that the
1104 construction of the closure goes away. 
1105
1106 So I have elaborated simplLazyBind to understand right-hand sides that look
1107 like
1108         /\ a1..an. body
1109
1110 and treat them specially. The real work is done in SimplUtils.abstractFloats,
1111 but there is quite a bit of plumbing in simplLazyBind as well.
1112
1113 The same transformation is good when there are lets in the body:
1114
1115         /\abc -> let(rec) x = e in b
1116    ==>
1117         let(rec) x' = /\abc -> let x = x' a b c in e
1118         in 
1119         /\abc -> let x = x' a b c in b
1120
1121 This is good because it can turn things like:
1122
1123         let f = /\a -> letrec g = ... g ... in g
1124 into
1125         letrec g' = /\a -> ... g' a ...
1126         in
1127         let f = /\ a -> g' a
1128
1129 which is better.  In effect, it means that big lambdas don't impede
1130 let-floating.
1131
1132 This optimisation is CRUCIAL in eliminating the junk introduced by
1133 desugaring mutually recursive definitions.  Don't eliminate it lightly!
1134
1135 [May 1999]  If we do this transformation *regardless* then we can
1136 end up with some pretty silly stuff.  For example, 
1137
1138         let 
1139             st = /\ s -> let { x1=r1 ; x2=r2 } in ...
1140         in ..
1141 becomes
1142         let y1 = /\s -> r1
1143             y2 = /\s -> r2
1144             st = /\s -> ...[y1 s/x1, y2 s/x2]
1145         in ..
1146
1147 Unless the "..." is a WHNF there is really no point in doing this.
1148 Indeed it can make things worse.  Suppose x1 is used strictly,
1149 and is of the form
1150
1151         x1* = case f y of { (a,b) -> e }
1152
1153 If we abstract this wrt the tyvar we then can't do the case inline
1154 as we would normally do.
1155
1156 That's why the whole transformation is part of the same process that
1157 floats let-bindings and constructor arguments out of RHSs.  In particular,
1158 it is guarded by the doFloatFromRhs call in simplLazyBind.
1159
1160
1161 \begin{code}
1162 abstractFloats :: [OutTyVar] -> SimplEnv -> OutExpr -> SimplM ([OutBind], OutExpr)
1163 abstractFloats main_tvs body_env body
1164   = ASSERT( notNull body_floats )
1165     do  { (subst, float_binds) <- mapAccumLM abstract empty_subst body_floats
1166         ; return (float_binds, CoreSubst.substExpr subst body) }
1167   where
1168     main_tv_set = mkVarSet main_tvs
1169     body_floats = getFloats body_env
1170     empty_subst = CoreSubst.mkEmptySubst (seInScope body_env)
1171
1172     abstract :: CoreSubst.Subst -> OutBind -> SimplM (CoreSubst.Subst, OutBind)
1173     abstract subst (NonRec id rhs)
1174       = do { (poly_id, poly_app) <- mk_poly tvs_here id
1175            ; let poly_rhs = mkLams tvs_here rhs'
1176                  subst'   = CoreSubst.extendIdSubst subst id poly_app
1177            ; return (subst', (NonRec poly_id poly_rhs)) }
1178       where
1179         rhs' = CoreSubst.substExpr subst rhs
1180         tvs_here | any isCoVar main_tvs = main_tvs      -- Note [Abstract over coercions]
1181                  | otherwise 
1182                  = varSetElems (main_tv_set `intersectVarSet` exprSomeFreeVars isTyVar rhs')
1183         
1184                 -- Abstract only over the type variables free in the rhs
1185                 -- wrt which the new binding is abstracted.  But the naive
1186                 -- approach of abstract wrt the tyvars free in the Id's type
1187                 -- fails. Consider:
1188                 --      /\ a b -> let t :: (a,b) = (e1, e2)
1189                 --                    x :: a     = fst t
1190                 --                in ...
1191                 -- Here, b isn't free in x's type, but we must nevertheless
1192                 -- abstract wrt b as well, because t's type mentions b.
1193                 -- Since t is floated too, we'd end up with the bogus:
1194                 --      poly_t = /\ a b -> (e1, e2)
1195                 --      poly_x = /\ a   -> fst (poly_t a *b*)
1196                 -- So for now we adopt the even more naive approach of
1197                 -- abstracting wrt *all* the tyvars.  We'll see if that
1198                 -- gives rise to problems.   SLPJ June 98
1199
1200     abstract subst (Rec prs)
1201        = do { (poly_ids, poly_apps) <- mapAndUnzipM (mk_poly tvs_here) ids
1202             ; let subst' = CoreSubst.extendSubstList subst (ids `zip` poly_apps)
1203                   poly_rhss = [mkLams tvs_here (CoreSubst.substExpr subst' rhs) | rhs <- rhss]
1204             ; return (subst', Rec (poly_ids `zip` poly_rhss)) }
1205        where
1206          (ids,rhss) = unzip prs
1207                 -- For a recursive group, it's a bit of a pain to work out the minimal
1208                 -- set of tyvars over which to abstract:
1209                 --      /\ a b c.  let x = ...a... in
1210                 --                 letrec { p = ...x...q...
1211                 --                          q = .....p...b... } in
1212                 --                 ...
1213                 -- Since 'x' is abstracted over 'a', the {p,q} group must be abstracted
1214                 -- over 'a' (because x is replaced by (poly_x a)) as well as 'b'.  
1215                 -- Since it's a pain, we just use the whole set, which is always safe
1216                 -- 
1217                 -- If you ever want to be more selective, remember this bizarre case too:
1218                 --      x::a = x
1219                 -- Here, we must abstract 'x' over 'a'.
1220          tvs_here = main_tvs
1221
1222     mk_poly tvs_here var
1223       = do { uniq <- getUniqueM
1224            ; let  poly_name = setNameUnique (idName var) uniq           -- Keep same name
1225                   poly_ty   = mkForAllTys tvs_here (idType var) -- But new type of course
1226                   poly_id   = transferPolyIdInfo var tvs_here $ -- Note [transferPolyIdInfo] in Id.lhs
1227                               mkLocalId poly_name poly_ty 
1228            ; return (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tvs_here)) }
1229                 -- In the olden days, it was crucial to copy the occInfo of the original var, 
1230                 -- because we were looking at occurrence-analysed but as yet unsimplified code!
1231                 -- In particular, we mustn't lose the loop breakers.  BUT NOW we are looking
1232                 -- at already simplified code, so it doesn't matter
1233                 -- 
1234                 -- It's even right to retain single-occurrence or dead-var info:
1235                 -- Suppose we started with  /\a -> let x = E in B
1236                 -- where x occurs once in B. Then we transform to:
1237                 --      let x' = /\a -> E in /\a -> let x* = x' a in B
1238                 -- where x* has an INLINE prag on it.  Now, once x* is inlined,
1239                 -- the occurrences of x' will be just the occurrences originally
1240                 -- pinned on x.
1241 \end{code}
1242
1243 Note [Abstract over coercions]
1244 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1245 If a coercion variable (g :: a ~ Int) is free in the RHS, then so is the
1246 type variable a.  Rather than sort this mess out, we simply bale out and abstract
1247 wrt all the type variables if any of them are coercion variables.
1248
1249
1250 Historical note: if you use let-bindings instead of a substitution, beware of this:
1251
1252                 -- Suppose we start with:
1253                 --
1254                 --      x = /\ a -> let g = G in E
1255                 --
1256                 -- Then we'll float to get
1257                 --
1258                 --      x = let poly_g = /\ a -> G
1259                 --          in /\ a -> let g = poly_g a in E
1260                 --
1261                 -- But now the occurrence analyser will see just one occurrence
1262                 -- of poly_g, not inside a lambda, so the simplifier will
1263                 -- PreInlineUnconditionally poly_g back into g!  Badk to square 1!
1264                 -- (I used to think that the "don't inline lone occurrences" stuff
1265                 --  would stop this happening, but since it's the *only* occurrence,
1266                 --  PreInlineUnconditionally kicks in first!)
1267                 --
1268                 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
1269                 --           to appear many times.  (NB: mkInlineMe eliminates
1270                 --           such notes on trivial RHSs, so do it manually.)
1271
1272 %************************************************************************
1273 %*                                                                      *
1274                 prepareAlts
1275 %*                                                                      *
1276 %************************************************************************
1277
1278 prepareAlts tries these things:
1279
1280 1.  If several alternatives are identical, merge them into
1281     a single DEFAULT alternative.  I've occasionally seen this 
1282     making a big difference:
1283
1284         case e of               =====>     case e of
1285           C _ -> f x                         D v -> ....v....
1286           D v -> ....v....                   DEFAULT -> f x
1287           DEFAULT -> f x
1288
1289    The point is that we merge common RHSs, at least for the DEFAULT case.
1290    [One could do something more elaborate but I've never seen it needed.]
1291    To avoid an expensive test, we just merge branches equal to the *first*
1292    alternative; this picks up the common cases
1293         a) all branches equal
1294         b) some branches equal to the DEFAULT (which occurs first)
1295
1296 2.  Case merging:
1297        case e of b {             ==>   case e of b {
1298          p1 -> rhs1                      p1 -> rhs1
1299          ...                             ...
1300          pm -> rhsm                      pm -> rhsm
1301          _  -> case b of b' {            pn -> let b'=b in rhsn
1302                      pn -> rhsn          ...
1303                      ...                 po -> let b'=b in rhso
1304                      po -> rhso          _  -> let b'=b in rhsd
1305                      _  -> rhsd
1306        }  
1307     
1308     which merges two cases in one case when -- the default alternative of
1309     the outer case scrutises the same variable as the outer case This
1310     transformation is called Case Merging.  It avoids that the same
1311     variable is scrutinised multiple times.
1312
1313
1314 The case where transformation (1) showed up was like this (lib/std/PrelCError.lhs):
1315
1316         x | p `is` 1 -> e1
1317           | p `is` 2 -> e2
1318         ...etc...
1319
1320 where @is@ was something like
1321         
1322         p `is` n = p /= (-1) && p == n
1323
1324 This gave rise to a horrible sequence of cases
1325
1326         case p of
1327           (-1) -> $j p
1328           1    -> e1
1329           DEFAULT -> $j p
1330
1331 and similarly in cascade for all the join points!
1332
1333 Note [Dead binders]
1334 ~~~~~~~~~~~~~~~~~~~~
1335 We do this *here*, looking at un-simplified alternatives, because we
1336 have to check that r doesn't mention the variables bound by the
1337 pattern in each alternative, so the binder-info is rather useful.
1338
1339 \begin{code}
1340 prepareAlts :: SimplEnv -> OutExpr -> OutId -> [InAlt] -> SimplM ([AltCon], [InAlt])
1341 prepareAlts env scrut case_bndr' alts
1342   = do  { dflags <- getDOptsSmpl
1343         ; alts <- combineIdenticalAlts case_bndr' alts
1344
1345         ; let (alts_wo_default, maybe_deflt) = findDefault alts
1346               alt_cons = [con | (con,_,_) <- alts_wo_default]
1347               imposs_deflt_cons = nub (imposs_cons ++ alt_cons)
1348                 -- "imposs_deflt_cons" are handled 
1349                 --   EITHER by the context, 
1350                 --   OR by a non-DEFAULT branch in this case expression.
1351
1352         ; default_alts <- prepareDefault dflags env case_bndr' mb_tc_app 
1353                                          imposs_deflt_cons maybe_deflt
1354
1355         ; let trimmed_alts = filterOut impossible_alt alts_wo_default
1356               merged_alts = mergeAlts trimmed_alts default_alts
1357                 -- We need the mergeAlts in case the new default_alt 
1358                 -- has turned into a constructor alternative.
1359                 -- The merge keeps the inner DEFAULT at the front, if there is one
1360                 -- and interleaves the alternatives in the right order
1361
1362         ; return (imposs_deflt_cons, merged_alts) }
1363   where
1364     mb_tc_app = splitTyConApp_maybe (idType case_bndr')
1365     Just (_, inst_tys) = mb_tc_app 
1366
1367     imposs_cons = case scrut of
1368                     Var v -> otherCons (idUnfolding v)
1369                     _     -> []
1370
1371     impossible_alt :: CoreAlt -> Bool
1372     impossible_alt (con, _, _) | con `elem` imposs_cons = True
1373     impossible_alt (DataAlt con, _, _) = dataConCannotMatch inst_tys con
1374     impossible_alt _                   = False
1375
1376
1377 --------------------------------------------------
1378 --      1. Merge identical branches
1379 --------------------------------------------------
1380 combineIdenticalAlts :: OutId -> [InAlt] -> SimplM [InAlt]
1381
1382 combineIdenticalAlts case_bndr ((_con1,bndrs1,rhs1) : con_alts)
1383   | all isDeadBinder bndrs1,                    -- Remember the default 
1384     length filtered_alts < length con_alts      -- alternative comes first
1385         -- Also Note [Dead binders]
1386   = do  { tick (AltMerge case_bndr)
1387         ; return ((DEFAULT, [], rhs1) : filtered_alts) }
1388   where
1389     filtered_alts        = filter keep con_alts
1390     keep (_con,bndrs,rhs) = not (all isDeadBinder bndrs && rhs `cheapEqExpr` rhs1)
1391
1392 combineIdenticalAlts _ alts = return alts
1393
1394 -------------------------------------------------------------------------
1395 --                      Prepare the default alternative
1396 -------------------------------------------------------------------------
1397 prepareDefault :: DynFlags
1398                -> SimplEnv
1399                -> OutId         -- Case binder; need just for its type. Note that as an
1400                                 --   OutId, it has maximum information; this is important.
1401                                 --   Test simpl013 is an example
1402                -> Maybe (TyCon, [Type]) -- Type of scrutinee, decomposed
1403                -> [AltCon]      -- These cons can't happen when matching the default
1404                -> Maybe InExpr  -- Rhs
1405                -> SimplM [InAlt]        -- Still unsimplified
1406                                         -- We use a list because it's what mergeAlts expects,
1407                                         -- And becuase case-merging can cause many to show up
1408
1409 ------- Merge nested cases ----------
1410 prepareDefault dflags env outer_bndr _bndr_ty imposs_cons (Just deflt_rhs)
1411   | dopt Opt_CaseMerge dflags
1412   , Case (Var inner_scrut_var) inner_bndr _ inner_alts <- deflt_rhs
1413   , DoneId inner_scrut_var' <- substId env inner_scrut_var
1414         -- Remember, inner_scrut_var is an InId, but outer_bndr is an OutId
1415   , inner_scrut_var' == outer_bndr
1416         -- NB: the substId means that if the outer scrutinee was a 
1417         --     variable, and inner scrutinee is the same variable, 
1418         --     then inner_scrut_var' will be outer_bndr
1419         --     via the magic of simplCaseBinder
1420   = do  { tick (CaseMerge outer_bndr)
1421
1422         ; let munge_rhs rhs = bindCaseBndr inner_bndr (Var outer_bndr) rhs
1423         ; return [(con, args, munge_rhs rhs) | (con, args, rhs) <- inner_alts,
1424                                                not (con `elem` imposs_cons) ]
1425                 -- NB: filter out any imposs_cons.  Example:
1426                 --      case x of 
1427                 --        A -> e1
1428                 --        DEFAULT -> case x of 
1429                 --                      A -> e2
1430                 --                      B -> e3
1431                 -- When we merge, we must ensure that e1 takes 
1432                 -- precedence over e2 as the value for A!  
1433         }
1434         -- Warning: don't call prepareAlts recursively!
1435         -- Firstly, there's no point, because inner alts have already had
1436         -- mkCase applied to them, so they won't have a case in their default
1437         -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr
1438         -- in munge_rhs may put a case into the DEFAULT branch!
1439
1440
1441 --------- Fill in known constructor -----------
1442 prepareDefault _ _ case_bndr (Just (tycon, inst_tys)) imposs_cons (Just deflt_rhs)
1443   |     -- This branch handles the case where we are 
1444         -- scrutinisng an algebraic data type
1445     isAlgTyCon tycon            -- It's a data type, tuple, or unboxed tuples.  
1446   , not (isNewTyCon tycon)      -- We can have a newtype, if we are just doing an eval:
1447                                 --      case x of { DEFAULT -> e }
1448                                 -- and we don't want to fill in a default for them!
1449   , Just all_cons <- tyConDataCons_maybe tycon
1450   , not (null all_cons)         -- This is a tricky corner case.  If the data type has no constructors,
1451                                 -- which GHC allows, then the case expression will have at most a default
1452                                 -- alternative.  We don't want to eliminate that alternative, because the
1453                                 -- invariant is that there's always one alternative.  It's more convenient
1454                                 -- to leave     
1455                                 --      case x of { DEFAULT -> e }     
1456                                 -- as it is, rather than transform it to
1457                                 --      error "case cant match"
1458                                 -- which would be quite legitmate.  But it's a really obscure corner, and
1459                                 -- not worth wasting code on.
1460   , let imposs_data_cons = [con | DataAlt con <- imposs_cons]   -- We now know it's a data type 
1461         impossible con  = con `elem` imposs_data_cons || dataConCannotMatch inst_tys con
1462   = case filterOut impossible all_cons of
1463         []    -> return []      -- Eliminate the default alternative
1464                                 -- altogether if it can't match
1465
1466         [con] ->        -- It matches exactly one constructor, so fill it in
1467                  do { tick (FillInCaseDefault case_bndr)
1468                     ; us <- getUniquesM
1469                     ; let (ex_tvs, co_tvs, arg_ids) =
1470                               dataConRepInstPat us con inst_tys
1471                     ; return [(DataAlt con, ex_tvs ++ co_tvs ++ arg_ids, deflt_rhs)] }
1472
1473         _ -> return [(DEFAULT, [], deflt_rhs)]
1474
1475   | debugIsOn, isAlgTyCon tycon, not (isOpenTyCon tycon), null (tyConDataCons tycon)
1476         -- This can legitimately happen for type families, so don't report that
1477   = pprTrace "prepareDefault" (ppr case_bndr <+> ppr tycon)
1478         $ return [(DEFAULT, [], deflt_rhs)]
1479
1480 --------- Catch-all cases -----------
1481 prepareDefault _dflags _env _case_bndr _bndr_ty _imposs_cons (Just deflt_rhs)
1482   = return [(DEFAULT, [], deflt_rhs)]
1483
1484 prepareDefault _dflags _env _case_bndr _bndr_ty _imposs_cons Nothing
1485   = return []   -- No default branch
1486 \end{code}
1487
1488
1489
1490 =================================================================================
1491
1492 mkCase tries these things
1493
1494 1.  Eliminate the case altogether if possible
1495
1496 2.  Case-identity:
1497
1498         case e of               ===> e
1499                 True  -> True;
1500                 False -> False
1501
1502     and similar friends.
1503
1504
1505 \begin{code}
1506 mkCase :: OutExpr -> OutId -> [OutAlt]  -- Increasing order
1507        -> SimplM OutExpr
1508
1509 --------------------------------------------------
1510 --      2. Identity case
1511 --------------------------------------------------
1512
1513 mkCase scrut case_bndr alts     -- Identity case
1514   | all identity_alt alts
1515   = do tick (CaseIdentity case_bndr)
1516        return (re_cast scrut)
1517   where
1518     identity_alt (con, args, rhs) = check_eq con args (de_cast rhs)
1519
1520     check_eq DEFAULT       _    (Var v)   = v == case_bndr
1521     check_eq (LitAlt lit') _    (Lit lit) = lit == lit'
1522     check_eq (DataAlt con) args rhs       = rhs `cheapEqExpr` mkConApp con (arg_tys ++ varsToCoreExprs args)
1523                                          || rhs `cheapEqExpr` Var case_bndr
1524     check_eq _ _ _ = False
1525
1526     arg_tys = map Type (tyConAppArgs (idType case_bndr))
1527
1528         -- We've seen this:
1529         --      case e of x { _ -> x `cast` c }
1530         -- And we definitely want to eliminate this case, to give
1531         --      e `cast` c
1532         -- So we throw away the cast from the RHS, and reconstruct
1533         -- it at the other end.  All the RHS casts must be the same
1534         -- if (all identity_alt alts) holds.
1535         -- 
1536         -- Don't worry about nested casts, because the simplifier combines them
1537     de_cast (Cast e _) = e
1538     de_cast e          = e
1539
1540     re_cast scrut = case head alts of
1541                         (_,_,Cast _ co) -> Cast scrut co
1542                         _               -> scrut
1543
1544
1545
1546 --------------------------------------------------
1547 --      Catch-all
1548 --------------------------------------------------
1549 mkCase scrut bndr alts = return (Case scrut bndr (coreAltsType alts) alts)
1550 \end{code}
1551
1552
1553 When adding auxiliary bindings for the case binder, it's worth checking if
1554 its dead, because it often is, and occasionally these mkCase transformations
1555 cascade rather nicely.
1556
1557 \begin{code}
1558 bindCaseBndr :: Id -> CoreExpr -> CoreExpr -> CoreExpr
1559 bindCaseBndr bndr rhs body
1560   | isDeadBinder bndr = body
1561   | otherwise         = bindNonRec bndr rhs body
1562 \end{code}