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