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