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