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