Make postInlineUnconditaionally more conservative
[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         mkLam, mkCase,
9
10         -- Inlining,
11         preInlineUnconditionally, postInlineUnconditionally, activeInline, activeRule,
12         inlineMode,
13
14         -- The continuation type
15         SimplCont(..), DupFlag(..), LetRhsFlag(..), 
16         contIsDupable, contResultType,
17         countValArgs, countArgs, pushContArgs,
18         mkBoringStop, mkLazyArgStop, mkRhsStop, contIsRhs, contIsRhsOrArg,
19         getContArgs, interestingCallContext, interestingArgContext,
20         interestingArg, isStrictType
21
22     ) where
23
24 #include "HsVersions.h"
25
26 import SimplEnv
27 import DynFlags         ( SimplifierSwitch(..), SimplifierMode(..),
28                           DynFlags, DynFlag(..), dopt )
29 import StaticFlags      ( opt_UF_UpdateInPlace, opt_SimplNoPreInlining,
30                           opt_RulesOff )
31 import CoreSyn
32 import CoreFVs          ( exprFreeVars )
33 import CoreUtils        ( cheapEqExpr, exprType, exprIsTrivial, 
34                           etaExpand, exprEtaExpandArity, bindNonRec, mkCoerce2,
35                           findDefault, exprOkForSpeculation, exprIsHNF, mergeAlts
36                         )
37 import Literal          ( mkStringLit )
38 import CoreUnfold       ( smallEnoughToInline )
39 import MkId             ( eRROR_ID )
40 import Id               ( Id, idType, isDataConWorkId, idOccInfo, isDictId, 
41                           isDeadBinder, idNewDemandInfo, isExportedId,
42                           idUnfolding, idNewStrictness, idInlinePragma, idHasRules
43                         )
44 import NewDemand        ( isStrictDmd, isBotRes, splitStrictSig )
45 import SimplMonad
46 import Type             ( Type, splitFunTys, dropForAlls, isStrictType,
47                           splitTyConApp_maybe, tyConAppArgs 
48                         )
49 import TyCon            ( tyConDataCons_maybe )
50 import DataCon          ( dataConRepArity )
51 import VarSet
52 import BasicTypes       ( TopLevelFlag(..), isNotTopLevel, OccInfo(..), isLoopBreaker, isOneOcc,
53                           Activation, isAlwaysActive, isActive )
54 import Util             ( lengthExceeds )
55 import Outputable
56 \end{code}
57
58
59 %************************************************************************
60 %*                                                                      *
61 \subsection{The continuation data type}
62 %*                                                                      *
63 %************************************************************************
64
65 \begin{code}
66 data SimplCont          -- Strict contexts
67   = Stop     OutType    -- Type of the result
68              LetRhsFlag
69              Bool       -- True <=> There is something interesting about
70                         --          the context, and hence the inliner
71                         --          should be a bit keener (see interestingCallContext)
72                         -- Two cases:
73                         -- (a) This is the RHS of a thunk whose type suggests
74                         --     that update-in-place would be possible
75                         -- (b) This is an argument of a function that has RULES
76                         --     Inlining the call might allow the rule to fire
77
78   | CoerceIt OutType                    -- The To-type, simplified
79              SimplCont
80
81   | ApplyTo  DupFlag 
82              InExpr SimplEnv            -- The argument, as yet unsimplified, 
83              SimplCont                  -- and its environment
84
85   | Select   DupFlag 
86              InId [InAlt] SimplEnv      -- The case binder, alts, and subst-env
87              SimplCont
88
89   | ArgOf    LetRhsFlag         -- An arbitrary strict context: the argument 
90                                 --      of a strict function, or a primitive-arg fn
91                                 --      or a PrimOp
92                                 -- No DupFlag, because we never duplicate it
93              OutType            -- arg_ty: type of the argument itself
94              OutType            -- cont_ty: the type of the expression being sought by the context
95                                 --      f (error "foo") ==> coerce t (error "foo")
96                                 -- when f is strict
97                                 -- We need to know the type t, to which to coerce.
98
99              (SimplEnv -> OutExpr -> SimplM FloatsWithExpr)     -- What to do with the result
100                                 -- The result expression in the OutExprStuff has type cont_ty
101
102 data LetRhsFlag = AnArg         -- It's just an argument not a let RHS
103                 | AnRhs         -- It's the RHS of a let (so please float lets out of big lambdas)
104
105 instance Outputable LetRhsFlag where
106   ppr AnArg = ptext SLIT("arg")
107   ppr AnRhs = ptext SLIT("rhs")
108
109 instance Outputable SimplCont where
110   ppr (Stop ty is_rhs _)             = ptext SLIT("Stop") <> brackets (ppr is_rhs) <+> ppr ty
111   ppr (ApplyTo dup arg se cont)      = (ptext SLIT("ApplyTo") <+> ppr dup <+> ppr arg) $$ ppr cont
112   ppr (ArgOf _ _ _ _)                = ptext SLIT("ArgOf...")
113   ppr (Select dup bndr alts se cont) = (ptext SLIT("Select") <+> ppr dup <+> ppr bndr) $$ 
114                                        (nest 4 (ppr alts)) $$ ppr cont
115   ppr (CoerceIt ty cont)             = (ptext SLIT("CoerceIt") <+> ppr ty) $$ ppr cont
116
117 data DupFlag = OkToDup | NoDup
118
119 instance Outputable DupFlag where
120   ppr OkToDup = ptext SLIT("ok")
121   ppr NoDup   = ptext SLIT("nodup")
122
123
124 -------------------
125 mkBoringStop :: OutType -> SimplCont
126 mkBoringStop ty = Stop ty AnArg False
127
128 mkLazyArgStop :: OutType -> Bool -> SimplCont
129 mkLazyArgStop ty has_rules = Stop ty AnArg (canUpdateInPlace ty || has_rules)
130
131 mkRhsStop :: OutType -> SimplCont
132 mkRhsStop ty = Stop ty AnRhs (canUpdateInPlace ty)
133
134 contIsRhs :: SimplCont -> Bool
135 contIsRhs (Stop _ AnRhs _)    = True
136 contIsRhs (ArgOf AnRhs _ _ _) = True
137 contIsRhs other               = False
138
139 contIsRhsOrArg (Stop _ _ _)    = True
140 contIsRhsOrArg (ArgOf _ _ _ _) = True
141 contIsRhsOrArg other           = False
142
143 -------------------
144 contIsDupable :: SimplCont -> Bool
145 contIsDupable (Stop _ _ _)               = True
146 contIsDupable (ApplyTo  OkToDup _ _ _)   = True
147 contIsDupable (Select   OkToDup _ _ _ _) = True
148 contIsDupable (CoerceIt _ cont)          = contIsDupable cont
149 contIsDupable other                      = False
150
151 -------------------
152 discardableCont :: SimplCont -> Bool
153 discardableCont (Stop _ _ _)        = False
154 discardableCont (CoerceIt _ cont)   = discardableCont cont
155 discardableCont other               = True
156
157 discardCont :: SimplCont        -- A continuation, expecting
158             -> SimplCont        -- Replace the continuation with a suitable coerce
159 discardCont cont = case cont of
160                      Stop to_ty is_rhs _ -> cont
161                      other               -> CoerceIt to_ty (mkBoringStop to_ty)
162                  where
163                    to_ty = contResultType cont
164
165 -------------------
166 contResultType :: SimplCont -> OutType
167 contResultType (Stop to_ty _ _)      = to_ty
168 contResultType (ArgOf _ _ to_ty _)   = to_ty
169 contResultType (ApplyTo _ _ _ cont)  = contResultType cont
170 contResultType (CoerceIt _ cont)     = contResultType cont
171 contResultType (Select _ _ _ _ cont) = contResultType cont
172
173 -------------------
174 countValArgs :: SimplCont -> Int
175 countValArgs (ApplyTo _ (Type ty) se cont) = countValArgs cont
176 countValArgs (ApplyTo _ val_arg   se cont) = 1 + countValArgs cont
177 countValArgs other                         = 0
178
179 countArgs :: SimplCont -> Int
180 countArgs (ApplyTo _ arg se cont) = 1 + countArgs cont
181 countArgs other                   = 0
182
183 -------------------
184 pushContArgs :: SimplEnv -> [OutArg] -> SimplCont -> SimplCont
185 -- Pushes args with the specified environment
186 pushContArgs env []           cont = cont
187 pushContArgs env (arg : args) cont = ApplyTo NoDup arg env (pushContArgs env args cont)
188 \end{code}
189
190
191 \begin{code}
192 getContArgs :: SwitchChecker
193             -> OutId -> SimplCont 
194             -> ([(InExpr, SimplEnv, Bool)],     -- Arguments; the Bool is true for strict args
195                 SimplCont)                      -- Remaining continuation
196 -- getContArgs id k = (args, k', inl)
197 --      args are the leading ApplyTo items in k
198 --      (i.e. outermost comes first)
199 --      augmented with demand info from the functionn
200 getContArgs chkr fun orig_cont
201   = let
202                 -- Ignore strictness info if the no-case-of-case
203                 -- flag is on.  Strictness changes evaluation order
204                 -- and that can change full laziness
205         stricts | switchIsOn chkr NoCaseOfCase = vanilla_stricts
206                 | otherwise                    = computed_stricts
207     in
208     go [] stricts orig_cont
209   where
210     ----------------------------
211
212         -- Type argument
213     go acc ss (ApplyTo _ arg@(Type _) se cont)
214         = go ((arg,se,False) : acc) ss cont
215                 -- NB: don't bother to instantiate the function type
216
217         -- Value argument
218     go acc (s:ss) (ApplyTo _ arg se cont)
219         = go ((arg,se,s) : acc) ss cont
220
221         -- We're run out of arguments, or else we've run out of demands
222         -- The latter only happens if the result is guaranteed bottom
223         -- This is the case for
224         --      * case (error "hello") of { ... }
225         --      * (error "Hello") arg
226         --      * f (error "Hello") where f is strict
227         --      etc
228         -- Then, especially in the first of these cases, we'd like to discard
229         -- the continuation, leaving just the bottoming expression.  But the
230         -- type might not be right, so we may have to add a coerce.
231     go acc ss cont 
232         | null ss && discardableCont cont = (reverse acc, discardCont cont)
233         | otherwise                       = (reverse acc, cont)
234
235     ----------------------------
236     vanilla_stricts, computed_stricts :: [Bool]
237     vanilla_stricts  = repeat False
238     computed_stricts = zipWith (||) fun_stricts arg_stricts
239
240     ----------------------------
241     (val_arg_tys, _) = splitFunTys (dropForAlls (idType fun))
242     arg_stricts      = map isStrictType val_arg_tys ++ repeat False
243         -- These argument types are used as a cheap and cheerful way to find
244         -- unboxed arguments, which must be strict.  But it's an InType
245         -- and so there might be a type variable where we expect a function
246         -- type (the substitution hasn't happened yet).  And we don't bother
247         -- doing the type applications for a polymorphic function.
248         -- Hence the splitFunTys*IgnoringForAlls*
249
250     ----------------------------
251         -- If fun_stricts is finite, it means the function returns bottom
252         -- after that number of value args have been consumed
253         -- Otherwise it's infinite, extended with False
254     fun_stricts
255       = case splitStrictSig (idNewStrictness fun) of
256           (demands, result_info)
257                 | not (demands `lengthExceeds` countValArgs orig_cont)
258                 ->      -- Enough args, use the strictness given.
259                         -- For bottoming functions we used to pretend that the arg
260                         -- is lazy, so that we don't treat the arg as an
261                         -- interesting context.  This avoids substituting
262                         -- top-level bindings for (say) strings into 
263                         -- calls to error.  But now we are more careful about
264                         -- inlining lone variables, so its ok (see SimplUtils.analyseCont)
265                    if isBotRes result_info then
266                         map isStrictDmd demands         -- Finite => result is bottom
267                    else
268                         map isStrictDmd demands ++ vanilla_stricts
269
270           other -> vanilla_stricts      -- Not enough args, or no strictness
271
272 -------------------
273 interestingArg :: OutExpr -> Bool
274         -- An argument is interesting if it has *some* structure
275         -- We are here trying to avoid unfolding a function that
276         -- is applied only to variables that have no unfolding
277         -- (i.e. they are probably lambda bound): f x y z
278         -- There is little point in inlining f here.
279 interestingArg (Var v)           = hasSomeUnfolding (idUnfolding v)
280                                         -- Was: isValueUnfolding (idUnfolding v')
281                                         -- But that seems over-pessimistic
282                                  || isDataConWorkId v
283                                         -- This accounts for an argument like
284                                         -- () or [], which is definitely interesting
285 interestingArg (Type _)          = False
286 interestingArg (App fn (Type _)) = interestingArg fn
287 interestingArg (Note _ a)        = interestingArg a
288 interestingArg other             = True
289         -- Consider     let x = 3 in f x
290         -- The substitution will contain (x -> ContEx 3), and we want to
291         -- to say that x is an interesting argument.
292         -- But consider also (\x. f x y) y
293         -- The substitution will contain (x -> ContEx y), and we want to say
294         -- that x is not interesting (assuming y has no unfolding)
295 \end{code}
296
297 Comment about interestingCallContext
298 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
299 We want to avoid inlining an expression where there can't possibly be
300 any gain, such as in an argument position.  Hence, if the continuation
301 is interesting (eg. a case scrutinee, application etc.) then we
302 inline, otherwise we don't.  
303
304 Previously some_benefit used to return True only if the variable was
305 applied to some value arguments.  This didn't work:
306
307         let x = _coerce_ (T Int) Int (I# 3) in
308         case _coerce_ Int (T Int) x of
309                 I# y -> ....
310
311 we want to inline x, but can't see that it's a constructor in a case
312 scrutinee position, and some_benefit is False.
313
314 Another example:
315
316 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
317
318 ....  case dMonadST _@_ x0 of (a,b,c) -> ....
319
320 we'd really like to inline dMonadST here, but we *don't* want to
321 inline if the case expression is just
322
323         case x of y { DEFAULT -> ... }
324
325 since we can just eliminate this case instead (x is in WHNF).  Similar
326 applies when x is bound to a lambda expression.  Hence
327 contIsInteresting looks for case expressions with just a single
328 default case.
329
330 \begin{code}
331 interestingCallContext :: Bool          -- False <=> no args at all
332                        -> Bool          -- False <=> no value args
333                        -> SimplCont -> Bool
334         -- The "lone-variable" case is important.  I spent ages
335         -- messing about with unsatisfactory varaints, but this is nice.
336         -- The idea is that if a variable appear all alone
337         --      as an arg of lazy fn, or rhs    Stop
338         --      as scrutinee of a case          Select
339         --      as arg of a strict fn           ArgOf
340         -- then we should not inline it (unless there is some other reason,
341         -- e.g. is is the sole occurrence).  We achieve this by making
342         -- interestingCallContext return False for a lone variable.
343         --
344         -- Why?  At least in the case-scrutinee situation, turning
345         --      let x = (a,b) in case x of y -> ...
346         -- into
347         --      let x = (a,b) in case (a,b) of y -> ...
348         -- and thence to 
349         --      let x = (a,b) in let y = (a,b) in ...
350         -- is bad if the binding for x will remain.
351         --
352         -- Another example: I discovered that strings
353         -- were getting inlined straight back into applications of 'error'
354         -- because the latter is strict.
355         --      s = "foo"
356         --      f = \x -> ...(error s)...
357
358         -- Fundamentally such contexts should not ecourage inlining because
359         -- the context can ``see'' the unfolding of the variable (e.g. case or a RULE)
360         -- so there's no gain.
361         --
362         -- However, even a type application or coercion isn't a lone variable.
363         -- Consider
364         --      case $fMonadST @ RealWorld of { :DMonad a b c -> c }
365         -- We had better inline that sucker!  The case won't see through it.
366         --
367         -- For now, I'm treating treating a variable applied to types 
368         -- in a *lazy* context "lone". The motivating example was
369         --      f = /\a. \x. BIG
370         --      g = /\a. \y.  h (f a)
371         -- There's no advantage in inlining f here, and perhaps
372         -- a significant disadvantage.  Hence some_val_args in the Stop case
373
374 interestingCallContext some_args some_val_args cont
375   = interesting cont
376   where
377     interesting (Select _ _ _ _ _)       = some_args
378     interesting (ApplyTo _ _ _ _)        = True -- Can happen if we have (coerce t (f x)) y
379                                                 -- Perhaps True is a bit over-keen, but I've
380                                                 -- seen (coerce f) x, where f has an INLINE prag,
381                                                 -- So we have to give some motivaiton for inlining it
382     interesting (ArgOf _ _ _ _)          = some_val_args
383     interesting (Stop ty _ interesting)  = some_val_args && interesting
384     interesting (CoerceIt _ cont)        = interesting cont
385         -- If this call is the arg of a strict function, the context
386         -- is a bit interesting.  If we inline here, we may get useful
387         -- evaluation information to avoid repeated evals: e.g.
388         --      x + (y * z)
389         -- Here the contIsInteresting makes the '*' keener to inline,
390         -- which in turn exposes a constructor which makes the '+' inline.
391         -- Assuming that +,* aren't small enough to inline regardless.
392         --
393         -- It's also very important to inline in a strict context for things
394         -- like
395         --              foldr k z (f x)
396         -- Here, the context of (f x) is strict, and if f's unfolding is
397         -- a build it's *great* to inline it here.  So we must ensure that
398         -- the context for (f x) is not totally uninteresting.
399
400
401 -------------------
402 interestingArgContext :: Id -> SimplCont -> Bool
403 -- If the argument has form (f x y), where x,y are boring,
404 -- and f is marked INLINE, then we don't want to inline f.
405 -- But if the context of the argument is
406 --      g (f x y) 
407 -- where g has rules, then we *do* want to inline f, in case it
408 -- exposes a rule that might fire.  Similarly, if the context is
409 --      h (g (f x x))
410 -- where h has rules, then we do want to inline f.
411 -- The interesting_arg_ctxt flag makes this happen; if it's
412 -- set, the inliner gets just enough keener to inline f 
413 -- regardless of how boring f's arguments are, if it's marked INLINE
414 --
415 -- The alternative would be to *always* inline an INLINE function,
416 -- regardless of how boring its context is; but that seems overkill
417 -- For example, it'd mean that wrapper functions were always inlined
418 interestingArgContext fn cont
419   = idHasRules fn || go cont
420   where
421     go (Select {})            = False
422     go (ApplyTo {})           = False
423     go (ArgOf {})             = True
424     go (CoerceIt _ c)         = go c
425     go (Stop _ _ interesting) = interesting
426
427 -------------------
428 canUpdateInPlace :: Type -> Bool
429 -- Consider   let x = <wurble> in ...
430 -- If <wurble> returns an explicit constructor, we might be able
431 -- to do update in place.  So we treat even a thunk RHS context
432 -- as interesting if update in place is possible.  We approximate
433 -- this by seeing if the type has a single constructor with a
434 -- small arity.  But arity zero isn't good -- we share the single copy
435 -- for that case, so no point in sharing.
436
437 canUpdateInPlace ty 
438   | not opt_UF_UpdateInPlace = False
439   | otherwise
440   = case splitTyConApp_maybe ty of 
441         Nothing         -> False 
442         Just (tycon, _) -> case tyConDataCons_maybe tycon of
443                                 Just [dc]  -> arity == 1 || arity == 2
444                                            where
445                                               arity = dataConRepArity dc
446                                 other -> False
447 \end{code}
448
449
450
451 %************************************************************************
452 %*                                                                      *
453 \subsection{Decisions about inlining}
454 %*                                                                      *
455 %************************************************************************
456
457 Inlining is controlled partly by the SimplifierMode switch.  This has two
458 settings:
459
460         SimplGently     (a) Simplifying before specialiser/full laziness
461                         (b) Simplifiying inside INLINE pragma
462                         (c) Simplifying the LHS of a rule
463                         (d) Simplifying a GHCi expression or Template 
464                                 Haskell splice
465
466         SimplPhase n    Used at all other times
467
468 The key thing about SimplGently is that it does no call-site inlining.
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 INLINE pragmas
483 ~~~~~~~~~~~~~~
484 SimplGently is also used as the mode to simplify inside an InlineMe note.
485
486 \begin{code}
487 inlineMode :: SimplifierMode
488 inlineMode = SimplGently
489 \end{code}
490
491 It really is important to switch off inlinings inside such
492 expressions.  Consider the following example 
493
494         let f = \pq -> BIG
495         in
496         let g = \y -> f y y
497             {-# INLINE g #-}
498         in ...g...g...g...g...g...
499
500 Now, if that's the ONLY occurrence of f, it will be inlined inside g,
501 and thence copied multiple times when g is inlined.
502
503
504 This function may be inlinined in other modules, so we
505 don't want to remove (by inlining) calls to functions that have
506 specialisations, or that may have transformation rules in an importing
507 scope.
508
509 E.g.    {-# INLINE f #-}
510                 f x = ...g...
511
512 and suppose that g is strict *and* has specialisations.  If we inline
513 g's wrapper, we deny f the chance of getting the specialised version
514 of g when f is inlined at some call site (perhaps in some other
515 module).
516
517 It's also important not to inline a worker back into a wrapper.
518 A wrapper looks like
519         wraper = inline_me (\x -> ...worker... )
520 Normally, the inline_me prevents the worker getting inlined into
521 the wrapper (initially, the worker's only call site!).  But,
522 if the wrapper is sure to be called, the strictness analyser will
523 mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
524 continuation.  That's why the keep_inline predicate returns True for
525 ArgOf continuations.  It shouldn't do any harm not to dissolve the
526 inline-me note under these circumstances.
527
528 Note that the result is that we do very little simplification
529 inside an InlineMe.  
530
531         all xs = foldr (&&) True xs
532         any p = all . map p  {-# INLINE any #-}
533
534 Problem: any won't get deforested, and so if it's exported and the
535 importer doesn't use the inlining, (eg passes it as an arg) then we
536 won't get deforestation at all.  We havn't solved this problem yet!
537
538
539 preInlineUnconditionally
540 ~~~~~~~~~~~~~~~~~~~~~~~~
541 @preInlineUnconditionally@ examines a bndr to see if it is used just
542 once in a completely safe way, so that it is safe to discard the
543 binding inline its RHS at the (unique) usage site, REGARDLESS of how
544 big the RHS might be.  If this is the case we don't simplify the RHS
545 first, but just inline it un-simplified.
546
547 This is much better than first simplifying a perhaps-huge RHS and then
548 inlining and re-simplifying it.  Indeed, it can be at least quadratically
549 better.  Consider
550
551         x1 = e1
552         x2 = e2[x1]
553         x3 = e3[x2]
554         ...etc...
555         xN = eN[xN-1]
556
557 We may end up simplifying e1 N times, e2 N-1 times, e3 N-3 times etc.
558 This can happen with cascades of functions too:
559
560         f1 = \x1.e1
561         f2 = \xs.e2[f1]
562         f3 = \xs.e3[f3]
563         ...etc...
564
565 THE MAIN INVARIANT is this:
566
567         ----  preInlineUnconditionally invariant -----
568    IF preInlineUnconditionally chooses to inline x = <rhs>
569    THEN doing the inlining should not change the occurrence
570         info for the free vars of <rhs>
571         ----------------------------------------------
572
573 For example, it's tempting to look at trivial binding like
574         x = y
575 and inline it unconditionally.  But suppose x is used many times,
576 but this is the unique occurrence of y.  Then inlining x would change
577 y's occurrence info, which breaks the invariant.  It matters: y
578 might have a BIG rhs, which will now be dup'd at every occurrenc of x.
579
580
581 Evne RHSs labelled InlineMe aren't caught here, because there might be
582 no benefit from inlining at the call site.
583
584 [Sept 01] Don't unconditionally inline a top-level thing, because that
585 can simply make a static thing into something built dynamically.  E.g.
586         x = (a,b)
587         main = \s -> h x
588
589 [Remember that we treat \s as a one-shot lambda.]  No point in
590 inlining x unless there is something interesting about the call site.
591
592 But watch out: if you aren't careful, some useful foldr/build fusion
593 can be lost (most notably in spectral/hartel/parstof) because the
594 foldr didn't see the build.  Doing the dynamic allocation isn't a big
595 deal, in fact, but losing the fusion can be.  But the right thing here
596 seems to be to do a callSiteInline based on the fact that there is
597 something interesting about the call site (it's strict).  Hmm.  That
598 seems a bit fragile.
599
600 Conclusion: inline top level things gaily until Phase 0 (the last
601 phase), at which point don't.
602
603 \begin{code}
604 preInlineUnconditionally :: SimplEnv -> TopLevelFlag -> InId -> InExpr -> Bool
605 preInlineUnconditionally env top_lvl bndr rhs
606   | not active             = False
607   | opt_SimplNoPreInlining = False
608   | otherwise = case idOccInfo bndr of
609                   IAmDead                    -> True    -- Happens in ((\x.1) v)
610                   OneOcc in_lam True int_cxt -> try_once in_lam int_cxt
611                   other                      -> False
612   where
613     phase = getMode env
614     active = case phase of
615                    SimplGently  -> isAlwaysActive prag
616                    SimplPhase n -> isActive n prag
617     prag = idInlinePragma bndr
618
619     try_once in_lam int_cxt     -- There's one textual occurrence
620         | not in_lam = isNotTopLevel top_lvl || early_phase
621         | otherwise  = int_cxt && canInlineInLam rhs
622
623 -- Be very careful before inlining inside a lambda, becuase (a) we must not 
624 -- invalidate occurrence information, and (b) we want to avoid pushing a
625 -- single allocation (here) into multiple allocations (inside lambda).  
626 -- Inlining a *function* with a single *saturated* call would be ok, mind you.
627 --      || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok)
628 --      where 
629 --              is_cheap = exprIsCheap rhs
630 --              ok = is_cheap && int_cxt
631
632         --      int_cxt         The context isn't totally boring
633         -- E.g. let f = \ab.BIG in \y. map f xs
634         --      Don't want to substitute for f, because then we allocate
635         --      its closure every time the \y is called
636         -- But: let f = \ab.BIG in \y. map (f y) xs
637         --      Now we do want to substitute for f, even though it's not 
638         --      saturated, because we're going to allocate a closure for 
639         --      (f y) every time round the loop anyhow.
640
641         -- canInlineInLam => free vars of rhs are (Once in_lam) or Many,
642         -- so substituting rhs inside a lambda doesn't change the occ info.
643         -- Sadly, not quite the same as exprIsHNF.
644     canInlineInLam (Lit l)              = True
645     canInlineInLam (Lam b e)            = isRuntimeVar b || canInlineInLam e
646     canInlineInLam (Note _ e)           = canInlineInLam e
647     canInlineInLam _                    = False
648
649     early_phase = case phase of
650                         SimplPhase 0 -> False
651                         other        -> True
652 -- If we don't have this early_phase test, consider
653 --      x = length [1,2,3]
654 -- The full laziness pass carefully floats all the cons cells to
655 -- top level, and preInlineUnconditionally floats them all back in.
656 -- Result is (a) static allocation replaced by dynamic allocation
657 --           (b) many simplifier iterations because this tickles
658 --               a related problem; only one inlining per pass
659 -- 
660 -- On the other hand, I have seen cases where top-level fusion is
661 -- lost if we don't inline top level thing (e.g. string constants)
662 -- Hence the test for phase zero (which is the phase for all the final
663 -- simplifications).  Until phase zero we take no special notice of
664 -- top level things, but then we become more leery about inlining
665 -- them.  
666
667 \end{code}
668
669 postInlineUnconditionally
670 ~~~~~~~~~~~~~~~~~~~~~~~~~
671 @postInlineUnconditionally@ decides whether to unconditionally inline
672 a thing based on the form of its RHS; in particular if it has a
673 trivial RHS.  If so, we can inline and discard the binding altogether.
674
675 NB: a loop breaker has must_keep_binding = True and non-loop-breakers
676 only have *forward* references Hence, it's safe to discard the binding
677         
678 NOTE: This isn't our last opportunity to inline.  We're at the binding
679 site right now, and we'll get another opportunity when we get to the
680 ocurrence(s)
681
682 Note that we do this unconditional inlining only for trival RHSs.
683 Don't inline even WHNFs inside lambdas; doing so may simply increase
684 allocation when the function is called. This isn't the last chance; see
685 NOTE above.
686
687 NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here Why?
688 Because we don't even want to inline them into the RHS of constructor
689 arguments. See NOTE above
690
691 NB: At one time even NOINLINE was ignored here: if the rhs is trivial
692 it's best to inline it anyway.  We often get a=E; b=a from desugaring,
693 with both a and b marked NOINLINE.  But that seems incompatible with
694 our new view that inlining is like a RULE, so I'm sticking to the 'active'
695 story for now.
696
697 \begin{code}
698 postInlineUnconditionally 
699     :: SimplEnv -> TopLevelFlag
700     -> InId             -- The binder (an OutId would be fine too)
701     -> OccInfo          -- From the InId
702     -> OutExpr
703     -> Unfolding
704     -> Bool
705 postInlineUnconditionally env top_lvl bndr occ_info rhs unfolding
706   | not active             = False
707   | isLoopBreaker occ_info = False
708   | isExportedId bndr      = False
709   | exprIsTrivial rhs      = True
710   | otherwise
711   = case occ_info of
712         -- The point of examining occ_info here is that for *non-values* 
713         -- that occur outside a lambda, the call-site inliner won't have
714         -- a chance (becuase it doesn't know that the thing
715         -- only occurs once).   The pre-inliner won't have gotten
716         -- it either, if the thing occurs in more than one branch
717         -- So the main target is things like
718         --      let x = f y in
719         --      case v of
720         --         True  -> case x of ...
721         --         False -> case x of ...
722         -- I'm not sure how important this is in practice
723       OneOcc in_lam one_br int_cxt      -- OneOcc => no work-duplication issue
724         ->     smallEnoughToInline unfolding    -- Small enough to dup
725                         -- ToDo: consider discount on smallEnoughToInline if int_cxt is true
726                         --
727                         -- NB: Do NOT inline arbitrarily big things, even if one_br is True
728                         -- Reason: doing so risks exponential behaviour.  We simplify a big
729                         --         expression, inline it, and simplify it again.  But if the
730                         --         very same thing happens in the big expression, we get 
731                         --         exponential cost!
732                         -- PRINCIPLE: when we've already simplified an expression once, 
733                         -- make sure that we only inline it if it's reasonably small.
734
735            &&  ((isNotTopLevel top_lvl && not in_lam) || 
736                         -- But outside a lambda, we want to be reasonably aggressive
737                         -- about inlining into multiple branches of case
738                         -- e.g. let x = <non-value> 
739                         --      in case y of { C1 -> ..x..; C2 -> ..x..; C3 -> ... } 
740                         -- Inlining can be a big win if C3 is the hot-spot, even if
741                         -- the uses in C1, C2 are not 'interesting'
742                         -- An example that gets worse if you add int_cxt here is 'clausify'
743
744                 (isCheapUnfolding unfolding && int_cxt))
745                         -- isCheap => acceptable work duplication; in_lam may be true
746                         -- int_cxt to prevent us inlining inside a lambda without some 
747                         -- good reason.  See the notes on int_cxt in preInlineUnconditionally
748
749       other -> False
750
751 -- Here's an example that we don't handle well:
752 --      let f = if b then Left (\x.BIG) else Right (\y.BIG)
753 --      in \y. ....case f of {...} ....
754 -- Here f is used just once, and duplicating the case work is fine (exprIsCheap).
755 -- But
756 -- * We can't preInlineUnconditionally because that woud invalidate
757 --   the occ info for b.  
758 -- * We can't postInlineUnconditionally because the RHS is big, and
759 --   that risks exponential behaviour
760 -- * We can't call-site inline, because the rhs is big
761 -- Alas!
762
763   where
764     active = case getMode env of
765                    SimplGently  -> isAlwaysActive prag
766                    SimplPhase n -> isActive n prag
767     prag = idInlinePragma bndr
768
769 activeInline :: SimplEnv -> OutId -> OccInfo -> Bool
770 activeInline env id occ
771   = case getMode env of
772       SimplGently -> isOneOcc occ && isAlwaysActive prag
773         -- No inlining at all when doing gentle stuff,
774         -- except for local things that occur once
775         -- The reason is that too little clean-up happens if you 
776         -- don't inline use-once things.   Also a bit of inlining is *good* for
777         -- full laziness; it can expose constant sub-expressions.
778         -- Example in spectral/mandel/Mandel.hs, where the mandelset 
779         -- function gets a useful let-float if you inline windowToViewport
780
781         -- NB: we used to have a second exception, for data con wrappers.
782         -- On the grounds that we use gentle mode for rule LHSs, and 
783         -- they match better when data con wrappers are inlined.
784         -- But that only really applies to the trivial wrappers (like (:)),
785         -- and they are now constructed as Compulsory unfoldings (in MkId)
786         -- so they'll happen anyway.
787
788       SimplPhase n -> isActive n prag
789   where
790     prag = idInlinePragma id
791
792 activeRule :: SimplEnv -> Maybe (Activation -> Bool)
793 -- Nothing => No rules at all
794 activeRule env
795   | opt_RulesOff = Nothing
796   | otherwise
797   = case getMode env of
798         SimplGently  -> Just isAlwaysActive
799                         -- Used to be Nothing (no rules in gentle mode)
800                         -- Main motivation for changing is that I wanted
801                         --      lift String ===> ...
802                         -- to work in Template Haskell when simplifying
803                         -- splices, so we get simpler code for literal strings
804         SimplPhase n -> Just (isActive n)
805 \end{code}      
806
807
808 %************************************************************************
809 %*                                                                      *
810 \subsection{Rebuilding a lambda}
811 %*                                                                      *
812 %************************************************************************
813
814 \begin{code}
815 mkLam :: SimplEnv -> [OutBinder] -> OutExpr -> SimplCont -> SimplM FloatsWithExpr
816 \end{code}
817
818 Try three things
819         a) eta reduction, if that gives a trivial expression
820         b) eta expansion [only if there are some value lambdas]
821         c) floating lets out through big lambdas 
822                 [only if all tyvar lambdas, and only if this lambda
823                  is the RHS of a let]
824
825 \begin{code}
826 mkLam env bndrs body cont
827  = getDOptsSmpl  `thenSmpl` \dflags ->
828    mkLam' dflags env bndrs body cont
829  where
830  mkLam' dflags env bndrs body cont
831    | dopt Opt_DoEtaReduction dflags,
832      Just etad_lam <- tryEtaReduce bndrs body
833    = tick (EtaReduction (head bndrs))   `thenSmpl_`
834      returnSmpl (emptyFloats env, etad_lam)
835
836    | dopt Opt_DoLambdaEtaExpansion dflags,
837      any isRuntimeVar bndrs
838    = tryEtaExpansion dflags body        `thenSmpl` \ body' ->
839      returnSmpl (emptyFloats env, mkLams bndrs body')
840
841 {-      Sept 01: I'm experimenting with getting the
842         full laziness pass to float out past big lambdsa
843  | all isTyVar bndrs,   -- Only for big lambdas
844    contIsRhs cont       -- Only try the rhs type-lambda floating
845                         -- if this is indeed a right-hand side; otherwise
846                         -- we end up floating the thing out, only for float-in
847                         -- to float it right back in again!
848  = tryRhsTyLam env bndrs body           `thenSmpl` \ (floats, body') ->
849    returnSmpl (floats, mkLams bndrs body')
850 -}
851
852    | otherwise 
853    = returnSmpl (emptyFloats env, mkLams bndrs body)
854 \end{code}
855
856
857 %************************************************************************
858 %*                                                                      *
859 \subsection{Eta expansion and reduction}
860 %*                                                                      *
861 %************************************************************************
862
863 We try for eta reduction here, but *only* if we get all the 
864 way to an exprIsTrivial expression.    
865 We don't want to remove extra lambdas unless we are going 
866 to avoid allocating this thing altogether
867
868 \begin{code}
869 tryEtaReduce :: [OutBinder] -> OutExpr -> Maybe OutExpr
870 tryEtaReduce bndrs body 
871         -- We don't use CoreUtils.etaReduce, because we can be more
872         -- efficient here:
873         --  (a) we already have the binders
874         --  (b) we can do the triviality test before computing the free vars
875   = go (reverse bndrs) body
876   where
877     go (b : bs) (App fun arg) | ok_arg b arg = go bs fun        -- Loop round
878     go []       fun           | ok_fun fun   = Just fun         -- Success!
879     go _        _                            = Nothing          -- Failure!
880
881     ok_fun fun =  exprIsTrivial fun
882                && not (any (`elemVarSet` (exprFreeVars fun)) bndrs)
883                && (exprIsHNF fun || all ok_lam bndrs)
884     ok_lam v = isTyVar v || isDictId v
885         -- The exprIsHNF is because eta reduction is not 
886         -- valid in general:  \x. bot  /=  bot
887         -- So we need to be sure that the "fun" is a value.
888         --
889         -- However, we always want to reduce (/\a -> f a) to f
890         -- This came up in a RULE: foldr (build (/\a -> g a))
891         --      did not match      foldr (build (/\b -> ...something complex...))
892         -- The type checker can insert these eta-expanded versions,
893         -- with both type and dictionary lambdas; hence the slightly 
894         -- ad-hoc isDictTy
895
896     ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
897 \end{code}
898
899
900         Try eta expansion for RHSs
901
902 We go for:
903    f = \x1..xn -> N  ==>   f = \x1..xn y1..ym -> N y1..ym
904                                  (n >= 0)
905
906 where (in both cases) 
907
908         * The xi can include type variables
909
910         * The yi are all value variables
911
912         * N is a NORMAL FORM (i.e. no redexes anywhere)
913           wanting a suitable number of extra args.
914
915 We may have to sandwich some coerces between the lambdas
916 to make the types work.   exprEtaExpandArity looks through coerces
917 when computing arity; and etaExpand adds the coerces as necessary when
918 actually computing the expansion.
919
920 \begin{code}
921 tryEtaExpansion :: DynFlags -> OutExpr -> SimplM OutExpr
922 -- There is at least one runtime binder in the binders
923 tryEtaExpansion dflags body
924   = getUniquesSmpl                      `thenSmpl` \ us ->
925     returnSmpl (etaExpand fun_arity us body (exprType body))
926   where
927     fun_arity = exprEtaExpandArity dflags body
928 \end{code}
929
930
931 %************************************************************************
932 %*                                                                      *
933 \subsection{Floating lets out of big lambdas}
934 %*                                                                      *
935 %************************************************************************
936
937 tryRhsTyLam tries this transformation, when the big lambda appears as
938 the RHS of a let(rec) binding:
939
940         /\abc -> let(rec) x = e in b
941    ==>
942         let(rec) x' = /\abc -> let x = x' a b c in e
943         in 
944         /\abc -> let x = x' a b c in b
945
946 This is good because it can turn things like:
947
948         let f = /\a -> letrec g = ... g ... in g
949 into
950         letrec g' = /\a -> ... g' a ...
951         in
952         let f = /\ a -> g' a
953
954 which is better.  In effect, it means that big lambdas don't impede
955 let-floating.
956
957 This optimisation is CRUCIAL in eliminating the junk introduced by
958 desugaring mutually recursive definitions.  Don't eliminate it lightly!
959
960 So far as the implementation is concerned:
961
962         Invariant: go F e = /\tvs -> F e
963         
964         Equalities:
965                 go F (Let x=e in b)
966                 = Let x' = /\tvs -> F e 
967                   in 
968                   go G b
969                 where
970                     G = F . Let x = x' tvs
971         
972                 go F (Letrec xi=ei in b)
973                 = Letrec {xi' = /\tvs -> G ei} 
974                   in
975                   go G b
976                 where
977                   G = F . Let {xi = xi' tvs}
978
979 [May 1999]  If we do this transformation *regardless* then we can
980 end up with some pretty silly stuff.  For example, 
981
982         let 
983             st = /\ s -> let { x1=r1 ; x2=r2 } in ...
984         in ..
985 becomes
986         let y1 = /\s -> r1
987             y2 = /\s -> r2
988             st = /\s -> ...[y1 s/x1, y2 s/x2]
989         in ..
990
991 Unless the "..." is a WHNF there is really no point in doing this.
992 Indeed it can make things worse.  Suppose x1 is used strictly,
993 and is of the form
994
995         x1* = case f y of { (a,b) -> e }
996
997 If we abstract this wrt the tyvar we then can't do the case inline
998 as we would normally do.
999
1000
1001 \begin{code}
1002 {-      Trying to do this in full laziness
1003
1004 tryRhsTyLam :: SimplEnv -> [OutTyVar] -> OutExpr -> SimplM FloatsWithExpr
1005 -- Call ensures that all the binders are type variables
1006
1007 tryRhsTyLam env tyvars body             -- Only does something if there's a let
1008   |  not (all isTyVar tyvars)
1009   || not (worth_it body)                -- inside a type lambda, 
1010   = returnSmpl (emptyFloats env, body)  -- and a WHNF inside that
1011
1012   | otherwise
1013   = go env (\x -> x) body
1014
1015   where
1016     worth_it e@(Let _ _) = whnf_in_middle e
1017     worth_it e           = False
1018
1019     whnf_in_middle (Let (NonRec x rhs) e) | isUnLiftedType (idType x) = False
1020     whnf_in_middle (Let _ e) = whnf_in_middle e
1021     whnf_in_middle e         = exprIsCheap e
1022
1023     main_tyvar_set = mkVarSet tyvars
1024
1025     go env fn (Let bind@(NonRec var rhs) body)
1026       | exprIsTrivial rhs
1027       = go env (fn . Let bind) body
1028
1029     go env fn (Let (NonRec var rhs) body)
1030       = mk_poly tyvars_here var                                                 `thenSmpl` \ (var', rhs') ->
1031         addAuxiliaryBind env (NonRec var' (mkLams tyvars_here (fn rhs)))        $ \ env -> 
1032         go env (fn . Let (mk_silly_bind var rhs')) body
1033
1034       where
1035
1036         tyvars_here = varSetElems (main_tyvar_set `intersectVarSet` exprSomeFreeVars isTyVar rhs)
1037                 -- Abstract only over the type variables free in the rhs
1038                 -- wrt which the new binding is abstracted.  But the naive
1039                 -- approach of abstract wrt the tyvars free in the Id's type
1040                 -- fails. Consider:
1041                 --      /\ a b -> let t :: (a,b) = (e1, e2)
1042                 --                    x :: a     = fst t
1043                 --                in ...
1044                 -- Here, b isn't free in x's type, but we must nevertheless
1045                 -- abstract wrt b as well, because t's type mentions b.
1046                 -- Since t is floated too, we'd end up with the bogus:
1047                 --      poly_t = /\ a b -> (e1, e2)
1048                 --      poly_x = /\ a   -> fst (poly_t a *b*)
1049                 -- So for now we adopt the even more naive approach of
1050                 -- abstracting wrt *all* the tyvars.  We'll see if that
1051                 -- gives rise to problems.   SLPJ June 98
1052
1053     go env fn (Let (Rec prs) body)
1054        = mapAndUnzipSmpl (mk_poly tyvars_here) vars     `thenSmpl` \ (vars', rhss') ->
1055          let
1056             gn body = fn (foldr Let body (zipWith mk_silly_bind vars rhss'))
1057             pairs   = vars' `zip` [mkLams tyvars_here (gn rhs) | rhs <- rhss]
1058          in
1059          addAuxiliaryBind env (Rec pairs)               $ \ env ->
1060          go env gn body 
1061        where
1062          (vars,rhss) = unzip prs
1063          tyvars_here = varSetElems (main_tyvar_set `intersectVarSet` exprsSomeFreeVars isTyVar (map snd prs))
1064                 -- See notes with tyvars_here above
1065
1066     go env fn body = returnSmpl (emptyFloats env, fn body)
1067
1068     mk_poly tyvars_here var
1069       = getUniqueSmpl           `thenSmpl` \ uniq ->
1070         let
1071             poly_name = setNameUnique (idName var) uniq         -- Keep same name
1072             poly_ty   = mkForAllTys tyvars_here (idType var)    -- But new type of course
1073             poly_id   = mkLocalId poly_name poly_ty 
1074
1075                 -- In the olden days, it was crucial to copy the occInfo of the original var, 
1076                 -- because we were looking at occurrence-analysed but as yet unsimplified code!
1077                 -- In particular, we mustn't lose the loop breakers.  BUT NOW we are looking
1078                 -- at already simplified code, so it doesn't matter
1079                 -- 
1080                 -- It's even right to retain single-occurrence or dead-var info:
1081                 -- Suppose we started with  /\a -> let x = E in B
1082                 -- where x occurs once in B. Then we transform to:
1083                 --      let x' = /\a -> E in /\a -> let x* = x' a in B
1084                 -- where x* has an INLINE prag on it.  Now, once x* is inlined,
1085                 -- the occurrences of x' will be just the occurrences originally
1086                 -- pinned on x.
1087         in
1088         returnSmpl (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tyvars_here))
1089
1090     mk_silly_bind var rhs = NonRec var (Note InlineMe rhs)
1091                 -- Suppose we start with:
1092                 --
1093                 --      x = /\ a -> let g = G in E
1094                 --
1095                 -- Then we'll float to get
1096                 --
1097                 --      x = let poly_g = /\ a -> G
1098                 --          in /\ a -> let g = poly_g a in E
1099                 --
1100                 -- But now the occurrence analyser will see just one occurrence
1101                 -- of poly_g, not inside a lambda, so the simplifier will
1102                 -- PreInlineUnconditionally poly_g back into g!  Badk to square 1!
1103                 -- (I used to think that the "don't inline lone occurrences" stuff
1104                 --  would stop this happening, but since it's the *only* occurrence,
1105                 --  PreInlineUnconditionally kicks in first!)
1106                 --
1107                 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
1108                 --           to appear many times.  (NB: mkInlineMe eliminates
1109                 --           such notes on trivial RHSs, so do it manually.)
1110 -}
1111 \end{code}
1112
1113 %************************************************************************
1114 %*                                                                      *
1115 \subsection{Case absorption and identity-case elimination}
1116 %*                                                                      *
1117 %************************************************************************
1118
1119 mkCase puts a case expression back together, trying various transformations first.
1120
1121 \begin{code}
1122 mkCase :: OutExpr -> OutId -> OutType
1123        -> [OutAlt]              -- Increasing order
1124        -> SimplM OutExpr
1125
1126 mkCase scrut case_bndr ty alts
1127   = getDOptsSmpl                        `thenSmpl` \dflags ->
1128     mkAlts dflags scrut case_bndr alts  `thenSmpl` \ better_alts ->
1129     mkCase1 scrut case_bndr ty better_alts
1130 \end{code}
1131
1132
1133 mkAlts tries these things:
1134
1135 1.  If several alternatives are identical, merge them into
1136     a single DEFAULT alternative.  I've occasionally seen this 
1137     making a big difference:
1138
1139         case e of               =====>     case e of
1140           C _ -> f x                         D v -> ....v....
1141           D v -> ....v....                   DEFAULT -> f x
1142           DEFAULT -> f x
1143
1144    The point is that we merge common RHSs, at least for the DEFAULT case.
1145    [One could do something more elaborate but I've never seen it needed.]
1146    To avoid an expensive test, we just merge branches equal to the *first*
1147    alternative; this picks up the common cases
1148         a) all branches equal
1149         b) some branches equal to the DEFAULT (which occurs first)
1150
1151 2.  Case merging:
1152        case e of b {             ==>   case e of b {
1153          p1 -> rhs1                      p1 -> rhs1
1154          ...                             ...
1155          pm -> rhsm                      pm -> rhsm
1156          _  -> case b of b' {            pn -> let b'=b in rhsn
1157                      pn -> rhsn          ...
1158                      ...                 po -> let b'=b in rhso
1159                      po -> rhso          _  -> let b'=b in rhsd
1160                      _  -> rhsd
1161        }  
1162     
1163     which merges two cases in one case when -- the default alternative of
1164     the outer case scrutises the same variable as the outer case This
1165     transformation is called Case Merging.  It avoids that the same
1166     variable is scrutinised multiple times.
1167
1168
1169 The case where transformation (1) showed up was like this (lib/std/PrelCError.lhs):
1170
1171         x | p `is` 1 -> e1
1172           | p `is` 2 -> e2
1173         ...etc...
1174
1175 where @is@ was something like
1176         
1177         p `is` n = p /= (-1) && p == n
1178
1179 This gave rise to a horrible sequence of cases
1180
1181         case p of
1182           (-1) -> $j p
1183           1    -> e1
1184           DEFAULT -> $j p
1185
1186 and similarly in cascade for all the join points!
1187
1188
1189
1190 \begin{code}
1191 --------------------------------------------------
1192 --      1. Merge identical branches
1193 --------------------------------------------------
1194 mkAlts dflags scrut case_bndr alts@((con1,bndrs1,rhs1) : con_alts)
1195   | all isDeadBinder bndrs1,                    -- Remember the default 
1196     length filtered_alts < length con_alts      -- alternative comes first
1197   = tick (AltMerge case_bndr)                   `thenSmpl_`
1198     returnSmpl better_alts
1199   where
1200     filtered_alts        = filter keep con_alts
1201     keep (con,bndrs,rhs) = not (all isDeadBinder bndrs && rhs `cheapEqExpr` rhs1)
1202     better_alts          = (DEFAULT, [], rhs1) : filtered_alts
1203
1204
1205 --------------------------------------------------
1206 --      2.  Merge nested cases
1207 --------------------------------------------------
1208
1209 mkAlts dflags scrut outer_bndr outer_alts
1210   | dopt Opt_CaseMerge dflags,
1211     (outer_alts_without_deflt, maybe_outer_deflt)   <- findDefault outer_alts,
1212     Just (Case (Var scrut_var) inner_bndr _ inner_alts) <- maybe_outer_deflt,
1213     scruting_same_var scrut_var
1214   = let
1215         munged_inner_alts = [(con, args, munge_rhs rhs) | (con, args, rhs) <- inner_alts]
1216         munge_rhs rhs = bindCaseBndr inner_bndr (Var outer_bndr) rhs
1217   
1218         new_alts = mergeAlts outer_alts_without_deflt munged_inner_alts
1219                 -- The merge keeps the inner DEFAULT at the front, if there is one
1220                 -- and eliminates any inner_alts that are shadowed by the outer_alts
1221     in
1222     tick (CaseMerge outer_bndr)                         `thenSmpl_`
1223     returnSmpl new_alts
1224         -- Warning: don't call mkAlts recursively!
1225         -- Firstly, there's no point, because inner alts have already had
1226         -- mkCase applied to them, so they won't have a case in their default
1227         -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr
1228         -- in munge_rhs may put a case into the DEFAULT branch!
1229   where
1230         -- We are scrutinising the same variable if it's
1231         -- the outer case-binder, or if the outer case scrutinises a variable
1232         -- (and it's the same).  Testing both allows us not to replace the
1233         -- outer scrut-var with the outer case-binder (Simplify.simplCaseBinder).
1234     scruting_same_var = case scrut of
1235                           Var outer_scrut -> \ v -> v == outer_bndr || v == outer_scrut
1236                           other           -> \ v -> v == outer_bndr
1237
1238 ------------------------------------------------
1239 --      Catch-all
1240 ------------------------------------------------
1241
1242 mkAlts dflags scrut case_bndr other_alts = returnSmpl other_alts
1243 \end{code}
1244
1245
1246
1247 =================================================================================
1248
1249 mkCase1 tries these things
1250
1251 1.  Eliminate the case altogether if possible
1252
1253 2.  Case-identity:
1254
1255         case e of               ===> e
1256                 True  -> True;
1257                 False -> False
1258
1259     and similar friends.
1260
1261
1262 Start with a simple situation:
1263
1264         case x# of      ===>   e[x#/y#]
1265           y# -> e
1266
1267 (when x#, y# are of primitive type, of course).  We can't (in general)
1268 do this for algebraic cases, because we might turn bottom into
1269 non-bottom!
1270
1271 Actually, we generalise this idea to look for a case where we're
1272 scrutinising a variable, and we know that only the default case can
1273 match.  For example:
1274 \begin{verbatim}
1275         case x of
1276           0#    -> ...
1277           other -> ...(case x of
1278                          0#    -> ...
1279                          other -> ...) ...
1280 \end{code}
1281 Here the inner case can be eliminated.  This really only shows up in
1282 eliminating error-checking code.
1283
1284 We also make sure that we deal with this very common case:
1285
1286         case e of 
1287           x -> ...x...
1288
1289 Here we are using the case as a strict let; if x is used only once
1290 then we want to inline it.  We have to be careful that this doesn't 
1291 make the program terminate when it would have diverged before, so we
1292 check that 
1293         - x is used strictly, or
1294         - e is already evaluated (it may so if e is a variable)
1295
1296 Lastly, we generalise the transformation to handle this:
1297
1298         case e of       ===> r
1299            True  -> r
1300            False -> r
1301
1302 We only do this for very cheaply compared r's (constructors, literals
1303 and variables).  If pedantic bottoms is on, we only do it when the
1304 scrutinee is a PrimOp which can't fail.
1305
1306 We do it *here*, looking at un-simplified alternatives, because we
1307 have to check that r doesn't mention the variables bound by the
1308 pattern in each alternative, so the binder-info is rather useful.
1309
1310 So the case-elimination algorithm is:
1311
1312         1. Eliminate alternatives which can't match
1313
1314         2. Check whether all the remaining alternatives
1315                 (a) do not mention in their rhs any of the variables bound in their pattern
1316            and  (b) have equal rhss
1317
1318         3. Check we can safely ditch the case:
1319                    * PedanticBottoms is off,
1320                 or * the scrutinee is an already-evaluated variable
1321                 or * the scrutinee is a primop which is ok for speculation
1322                         -- ie we want to preserve divide-by-zero errors, and
1323                         -- calls to error itself!
1324
1325                 or * [Prim cases] the scrutinee is a primitive variable
1326
1327                 or * [Alg cases] the scrutinee is a variable and
1328                      either * the rhs is the same variable
1329                         (eg case x of C a b -> x  ===>   x)
1330                      or     * there is only one alternative, the default alternative,
1331                                 and the binder is used strictly in its scope.
1332                                 [NB this is helped by the "use default binder where
1333                                  possible" transformation; see below.]
1334
1335
1336 If so, then we can replace the case with one of the rhss.
1337
1338 Further notes about case elimination
1339 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1340 Consider:       test :: Integer -> IO ()
1341                 test = print
1342
1343 Turns out that this compiles to:
1344     Print.test
1345       = \ eta :: Integer
1346           eta1 :: State# RealWorld ->
1347           case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT ->
1348           case hPutStr stdout
1349                  (PrelNum.jtos eta ($w[] @ Char))
1350                  eta1
1351           of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s  }}
1352
1353 Notice the strange '<' which has no effect at all. This is a funny one.  
1354 It started like this:
1355
1356 f x y = if x < 0 then jtos x
1357           else if y==0 then "" else jtos x
1358
1359 At a particular call site we have (f v 1).  So we inline to get
1360
1361         if v < 0 then jtos x 
1362         else if 1==0 then "" else jtos x
1363
1364 Now simplify the 1==0 conditional:
1365
1366         if v<0 then jtos v else jtos v
1367
1368 Now common-up the two branches of the case:
1369
1370         case (v<0) of DEFAULT -> jtos v
1371
1372 Why don't we drop the case?  Because it's strict in v.  It's technically
1373 wrong to drop even unnecessary evaluations, and in practice they
1374 may be a result of 'seq' so we *definitely* don't want to drop those.
1375 I don't really know how to improve this situation.
1376
1377
1378 \begin{code}
1379 --------------------------------------------------
1380 --      0. Check for empty alternatives
1381 --------------------------------------------------
1382
1383 -- This isn't strictly an error.  It's possible that the simplifer might "see"
1384 -- that an inner case has no accessible alternatives before it "sees" that the
1385 -- entire branch of an outer case is inaccessible.  So we simply
1386 -- put an error case here insteadd
1387 mkCase1 scrut case_bndr ty []
1388   = pprTrace "mkCase1: null alts" (ppr case_bndr <+> ppr scrut) $
1389     return (mkApps (Var eRROR_ID)
1390                    [Type ty, Lit (mkStringLit "Impossible alternative")])
1391
1392 --------------------------------------------------
1393 --      1. Eliminate the case altogether if poss
1394 --------------------------------------------------
1395
1396 mkCase1 scrut case_bndr ty [(con,bndrs,rhs)]
1397   -- See if we can get rid of the case altogether
1398   -- See the extensive notes on case-elimination above
1399   -- mkCase made sure that if all the alternatives are equal, 
1400   -- then there is now only one (DEFAULT) rhs
1401  |  all isDeadBinder bndrs,
1402
1403         -- Check that the scrutinee can be let-bound instead of case-bound
1404     exprOkForSpeculation scrut
1405                 -- OK not to evaluate it
1406                 -- This includes things like (==# a# b#)::Bool
1407                 -- so that we simplify 
1408                 --      case ==# a# b# of { True -> x; False -> x }
1409                 -- to just
1410                 --      x
1411                 -- This particular example shows up in default methods for
1412                 -- comparision operations (e.g. in (>=) for Int.Int32)
1413         || exprIsHNF scrut                      -- It's already evaluated
1414         || var_demanded_later scrut             -- It'll be demanded later
1415
1416 --      || not opt_SimplPedanticBottoms)        -- Or we don't care!
1417 --      We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1418 --      but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1419 --      its argument:  case x of { y -> dataToTag# y }
1420 --      Here we must *not* discard the case, because dataToTag# just fetches the tag from
1421 --      the info pointer.  So we'll be pedantic all the time, and see if that gives any
1422 --      other problems
1423 --      Also we don't want to discard 'seq's
1424   = tick (CaseElim case_bndr)                   `thenSmpl_` 
1425     returnSmpl (bindCaseBndr case_bndr scrut rhs)
1426
1427   where
1428         -- The case binder is going to be evaluated later, 
1429         -- and the scrutinee is a simple variable
1430     var_demanded_later (Var v) = isStrictDmd (idNewDemandInfo case_bndr)
1431     var_demanded_later other   = False
1432
1433
1434 --------------------------------------------------
1435 --      2. Identity case
1436 --------------------------------------------------
1437
1438 mkCase1 scrut case_bndr ty alts -- Identity case
1439   | all identity_alt alts
1440   = tick (CaseIdentity case_bndr)               `thenSmpl_`
1441     returnSmpl (re_note scrut)
1442   where
1443     identity_alt (con, args, rhs) = de_note rhs `cheapEqExpr` identity_rhs con args
1444
1445     identity_rhs (DataAlt con) args = mkConApp con (arg_tys ++ map varToCoreExpr args)
1446     identity_rhs (LitAlt lit)  _    = Lit lit
1447     identity_rhs DEFAULT       _    = Var case_bndr
1448
1449     arg_tys = map Type (tyConAppArgs (idType case_bndr))
1450
1451         -- We've seen this:
1452         --      case coerce T e of x { _ -> coerce T' x }
1453         -- And we definitely want to eliminate this case!
1454         -- So we throw away notes from the RHS, and reconstruct
1455         -- (at least an approximation) at the other end
1456     de_note (Note _ e) = de_note e
1457     de_note e          = e
1458
1459         -- re_note wraps a coerce if it might be necessary
1460     re_note scrut = case head alts of
1461                         (_,_,rhs1@(Note _ _)) -> mkCoerce2 (exprType rhs1) (idType case_bndr) scrut
1462                         other                 -> scrut
1463
1464
1465 --------------------------------------------------
1466 --      Catch-all
1467 --------------------------------------------------
1468 mkCase1 scrut bndr ty alts = returnSmpl (Case scrut bndr ty alts)
1469 \end{code}
1470
1471
1472 When adding auxiliary bindings for the case binder, it's worth checking if
1473 its dead, because it often is, and occasionally these mkCase transformations
1474 cascade rather nicely.
1475
1476 \begin{code}
1477 bindCaseBndr bndr rhs body
1478   | isDeadBinder bndr = body
1479   | otherwise         = bindNonRec bndr rhs body
1480 \end{code}