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