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