[project @ 2000-05-23 11:35:36 by simonpj]
[ghc-hetmet.git] / ghc / compiler / simplCore / SimplUtils.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1993-1998
3 %
4 \section[SimplUtils]{The simplifier utilities}
5
6 \begin{code}
7 module SimplUtils (
8         simplBinder, simplBinders, simplIds,
9         transformRhs,
10         mkCase, findAlt, findDefault,
11
12         -- The continuation type
13         SimplCont(..), DupFlag(..), contIsDupable, contResultType,
14         pushArgs, discardCont, countValArgs, countArgs,
15         analyseCont, discardInline
16
17     ) where
18
19 #include "HsVersions.h"
20
21 import BinderInfo
22 import CmdLineOpts      ( opt_SimplDoLambdaEtaExpansion, opt_SimplCaseMerge )
23 import CoreSyn
24 import PprCore          ( {- instance Outputable Expr -} )
25 import CoreUnfold       ( isValueUnfolding )
26 import CoreFVs          ( exprFreeVars )
27 import CoreUtils        ( exprIsTrivial, cheapEqExpr, exprType, exprIsCheap, exprEtaExpandArity, bindNonRec )
28 import Subst            ( InScopeSet, mkSubst, substBndrs, substBndr, substIds, lookupIdSubst )
29 import Id               ( Id, idType, isId, idName, 
30                           idOccInfo, idUnfolding,
31                           mkId, idInfo
32                         )
33 import IdInfo           ( arityLowerBound, setOccInfo, vanillaIdInfo )
34 import Maybes           ( maybeToBool, catMaybes )
35 import Name             ( isLocalName, setNameUnique )
36 import SimplMonad
37 import Type             ( Type, tyVarsOfType, tyVarsOfTypes, mkForAllTys, seqType, repType,
38                           splitTyConApp_maybe, splitAlgTyConApp_maybe, mkTyVarTys, applyTys, splitFunTys, mkFunTys
39                         )
40 import PprType          ( {- instance Outputable Type -} )
41 import DataCon          ( dataConRepArity )
42 import TysPrim          ( statePrimTyCon )
43 import Var              ( setVarUnique )
44 import VarSet
45 import VarEnv           ( SubstEnv, SubstResult(..) )
46 import UniqSupply       ( splitUniqSupply, uniqFromSupply )
47 import Util             ( zipWithEqual, mapAccumL )
48 import Outputable
49 \end{code}
50
51
52 %************************************************************************
53 %*                                                                      *
54 \subsection{The continuation data type}
55 %*                                                                      *
56 %************************************************************************
57
58 \begin{code}
59 data SimplCont          -- Strict contexts
60   = Stop OutType                -- Type of the result
61
62   | CoerceIt OutType                    -- The To-type, simplified
63              SimplCont
64
65   | InlinePlease                        -- This continuation makes a function very
66              SimplCont                  -- keen to inline itelf
67
68   | ApplyTo  DupFlag 
69              InExpr SubstEnv            -- The argument, as yet unsimplified, 
70              SimplCont                  -- and its subst-env
71
72   | Select   DupFlag 
73              InId [InAlt] SubstEnv      -- The case binder, alts, and subst-env
74              SimplCont
75
76   | ArgOf    DupFlag            -- An arbitrary strict context: the argument 
77                                 --      of a strict function, or a primitive-arg fn
78                                 --      or a PrimOp
79              OutType            -- The type of the expression being sought by the context
80                                 --      f (error "foo") ==> coerce t (error "foo")
81                                 -- when f is strict
82                                 -- We need to know the type t, to which to coerce.
83              (OutExpr -> SimplM OutExprStuff)   -- What to do with the result
84
85 instance Outputable SimplCont where
86   ppr (Stop _)                       = ptext SLIT("Stop")
87   ppr (ApplyTo dup arg se cont)      = (ptext SLIT("ApplyTo") <+> ppr dup <+> ppr arg) $$ ppr cont
88   ppr (ArgOf   dup _ _)              = ptext SLIT("ArgOf...") <+> ppr dup
89   ppr (Select dup bndr alts se cont) = (ptext SLIT("Select") <+> ppr dup <+> ppr bndr) $$ 
90                                        (nest 4 (ppr alts)) $$ ppr cont
91   ppr (CoerceIt ty cont)             = (ptext SLIT("CoerceIt") <+> ppr ty) $$ ppr cont
92   ppr (InlinePlease cont)            = ptext SLIT("InlinePlease") $$ ppr cont
93
94 data DupFlag = OkToDup | NoDup
95
96 instance Outputable DupFlag where
97   ppr OkToDup = ptext SLIT("ok")
98   ppr NoDup   = ptext SLIT("nodup")
99
100 contIsDupable :: SimplCont -> Bool
101 contIsDupable (Stop _)                   = True
102 contIsDupable (ApplyTo  OkToDup _ _ _)   = True
103 contIsDupable (ArgOf    OkToDup _ _)     = True
104 contIsDupable (Select   OkToDup _ _ _ _) = True
105 contIsDupable (CoerceIt _ cont)          = contIsDupable cont
106 contIsDupable (InlinePlease cont)        = contIsDupable cont
107 contIsDupable other                      = False
108
109 pushArgs :: SubstEnv -> [InExpr] -> SimplCont -> SimplCont
110 pushArgs se []         cont = cont
111 pushArgs se (arg:args) cont = ApplyTo NoDup arg se (pushArgs se args cont)
112
113 discardCont :: SimplCont        -- A continuation, expecting
114             -> SimplCont        -- Replace the continuation with a suitable coerce
115 discardCont (Stop to_ty) = Stop to_ty
116 discardCont cont         = CoerceIt to_ty (Stop to_ty)
117                          where
118                            to_ty = contResultType cont
119
120 contResultType :: SimplCont -> OutType
121 contResultType (Stop to_ty)          = to_ty
122 contResultType (ArgOf _ to_ty _)     = to_ty
123 contResultType (ApplyTo _ _ _ cont)  = contResultType cont
124 contResultType (CoerceIt _ cont)     = contResultType cont
125 contResultType (InlinePlease cont)   = contResultType cont
126 contResultType (Select _ _ _ _ cont) = contResultType cont
127
128 countValArgs :: SimplCont -> Int
129 countValArgs (ApplyTo _ (Type ty) se cont) = countValArgs cont
130 countValArgs (ApplyTo _ val_arg   se cont) = 1 + countValArgs cont
131 countValArgs other                         = 0
132
133 countArgs :: SimplCont -> Int
134 countArgs (ApplyTo _ arg se cont) = 1 + countArgs cont
135 countArgs other                   = 0
136 \end{code}
137
138
139 Comment about analyseCont
140 ~~~~~~~~~~~~~~~~~~~~~~~~~
141 We want to avoid inlining an expression where there can't possibly be
142 any gain, such as in an argument position.  Hence, if the continuation
143 is interesting (eg. a case scrutinee, application etc.) then we
144 inline, otherwise we don't.  
145
146 Previously some_benefit used to return True only if the variable was
147 applied to some value arguments.  This didn't work:
148
149         let x = _coerce_ (T Int) Int (I# 3) in
150         case _coerce_ Int (T Int) x of
151                 I# y -> ....
152
153 we want to inline x, but can't see that it's a constructor in a case
154 scrutinee position, and some_benefit is False.
155
156 Another example:
157
158 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
159
160 ....  case dMonadST _@_ x0 of (a,b,c) -> ....
161
162 we'd really like to inline dMonadST here, but we *don't* want to
163 inline if the case expression is just
164
165         case x of y { DEFAULT -> ... }
166
167 since we can just eliminate this case instead (x is in WHNF).  Similar
168 applies when x is bound to a lambda expression.  Hence
169 contIsInteresting looks for case expressions with just a single
170 default case.
171
172 \begin{code}
173 analyseCont :: InScopeSet -> SimplCont
174             -> ([Bool],         -- Arg-info flags; one for each value argument
175                 Bool,           -- Context of the result of the call is interesting
176                 Bool)           -- There was an InlinePlease 
177
178 analyseCont in_scope cont 
179   = case cont of
180         -- The "lone-variable" case is important.  I spent ages
181         -- messing about with unsatisfactory varaints, but this is nice.
182         -- The idea is that if a variable appear all alone
183         --      as an arg of lazy fn, or rhs    Stop
184         --      as scrutinee of a case          Select
185         --      as arg of a strict fn           ArgOf
186         -- then we should not inline it (unless there is some other reason,
187         -- e.g. is is the sole occurrence).  
188         -- Why not?  At least in the case-scrutinee situation, turning
189         --      case x of y -> ...
190         -- into
191         --      let y = (a,b) in ...
192         -- is bad if the binding for x will remain.
193         --
194         -- Another example: I discovered that strings
195         -- were getting inlined straight back into applications of 'error'
196         -- because the latter is strict.
197         --      s = "foo"
198         --      f = \x -> ...(error s)...
199
200         -- Fundamentally such contexts should not ecourage inlining becuase
201         -- the context can ``see'' the unfolding of the variable (e.g. case or a RULE)
202         -- so there's no gain.
203         --
204         -- However, even a type application isn't a lone variable.  Consider
205         --      case $fMonadST @ RealWorld of { :DMonad a b c -> c }
206         -- We had better inline that sucker!  The case won't see through it.
207
208       (Stop _)                    -> boring_result              -- Don't inline a lone variable
209       (Select _ _ _ _ _)          -> boring_result              -- Ditto
210       (ArgOf _ _ _)               -> boring_result              -- Ditto
211       (ApplyTo _ (Type _) _ cont) -> analyse_ty_app cont
212       other                       -> analyse_app cont
213   where
214     boring_result = ([], False, False)
215
216                 -- For now, I'm treating not treating a variable applied to types as
217                 -- "lone". The motivating example was
218                 --      f = /\a. \x. BIG
219                 --      g = /\a. \y.  h (f a)
220                 -- There's no advantage in inlining f here, and perhaps
221                 -- a significant disadvantage.
222     analyse_ty_app (Stop _)                     = boring_result
223     analyse_ty_app (ArgOf _ _ _)                = boring_result
224     analyse_ty_app (Select _ _ _ _ _)           = ([], True, False)     -- See the $fMonadST example above
225     analyse_ty_app (ApplyTo _ (Type _) _ cont)  = analyse_ty_app cont
226     analyse_ty_app cont                         = analyse_app cont
227
228     analyse_app (InlinePlease cont)  
229         = case analyse_app cont of
230                  (infos, icont, inline) -> (infos, icont, True)
231
232     analyse_app (ApplyTo _ arg subst cont) 
233         | isValArg arg = case analyse_app cont of
234                            (infos, icont, inline) -> (analyse_arg subst arg : infos, icont, inline)
235         | otherwise    = analyse_app cont
236
237     analyse_app cont = ([], interesting_call_context cont, False)
238
239         -- An argument is interesting if it has *some* structure
240         -- We are here trying to avoid unfolding a function that
241         -- is applied only to variables that have no unfolding
242         -- (i.e. they are probably lambda bound): f x y z
243         -- There is little point in inlining f here.
244     analyse_arg :: SubstEnv -> InExpr -> Bool
245     analyse_arg subst (Var v)           = case lookupIdSubst (mkSubst in_scope subst) v of
246                                                 DoneId v' _ -> isValueUnfolding (idUnfolding v')
247                                                 other       -> False
248     analyse_arg subst (Type _)          = False
249     analyse_arg subst (App fn (Type _)) = analyse_arg subst fn
250     analyse_arg subst (Note _ a)        = analyse_arg subst a
251     analyse_arg subst other             = True
252
253     interesting_call_context (Stop ty)                   = canUpdateInPlace ty
254     interesting_call_context (InlinePlease _)            = True
255     interesting_call_context (Select _ _ _ _ _)          = True
256     interesting_call_context (CoerceIt _ cont)           = interesting_call_context cont
257     interesting_call_context (ApplyTo _ (Type _) _ cont) = interesting_call_context cont
258     interesting_call_context (ApplyTo _ _        _ _)    = True
259     interesting_call_context (ArgOf _ _ _)               = True
260         -- If this call is the arg of a strict function, the context
261         -- is a bit interesting.  If we inline here, we may get useful
262         -- evaluation information to avoid repeated evals: e.g.
263         --      x + (y * z)
264         -- Here the contIsInteresting makes the '*' keener to inline,
265         -- which in turn exposes a constructor which makes the '+' inline.
266         -- Assuming that +,* aren't small enough to inline regardless.
267         --
268         -- It's also very important to inline in a strict context for things
269         -- like
270         --              foldr k z (f x)
271         -- Here, the context of (f x) is strict, and if f's unfolding is
272         -- a build it's *great* to inline it here.  So we must ensure that
273         -- the context for (f x) is not totally uninteresting.
274
275
276 discardInline :: SimplCont -> SimplCont
277 discardInline (InlinePlease cont)  = cont
278 discardInline (ApplyTo d e s cont) = ApplyTo d e s (discardInline cont)
279 discardInline cont                 = cont
280
281 -- Consider   let x = <wurble> in ...
282 -- If <wurble> returns an explicit constructor, we might be able
283 -- to do update in place.  So we treat even a thunk RHS context
284 -- as interesting if update in place is possible.  We approximate
285 -- this by seeing if the type has a single constructor with a
286 -- small arity.  But arity zero isn't good -- we share the single copy
287 -- for that case, so no point in sharing.
288
289 -- Note the repType: we want to look through newtypes for this purpose
290
291 canUpdateInPlace ty = case splitAlgTyConApp_maybe (repType ty) of
292                         Just (_, _, [dc]) -> arity == 1 || arity == 2
293                                           where
294                                              arity = dataConRepArity dc
295                         other -> False
296 \end{code}
297
298
299
300 %************************************************************************
301 %*                                                                      *
302 \section{Dealing with a single binder}
303 %*                                                                      *
304 %************************************************************************
305
306 \begin{code}
307 simplBinders :: [InBinder] -> ([OutBinder] -> SimplM a) -> SimplM a
308 simplBinders bndrs thing_inside
309   = getSubst            `thenSmpl` \ subst ->
310     let
311         (subst', bndrs') = substBndrs subst bndrs
312     in
313     seqBndrs bndrs'     `seq`
314     setSubst subst' (thing_inside bndrs')
315
316 simplBinder :: InBinder -> (OutBinder -> SimplM a) -> SimplM a
317 simplBinder bndr thing_inside
318   = getSubst            `thenSmpl` \ subst ->
319     let
320         (subst', bndr') = substBndr subst bndr
321     in
322     seqBndr bndr'       `seq`
323     setSubst subst' (thing_inside bndr')
324
325
326 -- Same semantics as simplBinders, but a little less 
327 -- plumbing and hence a little more efficient.
328 -- Maybe not worth the candle?
329 simplIds :: [InBinder] -> ([OutBinder] -> SimplM a) -> SimplM a
330 simplIds ids thing_inside
331   = getSubst            `thenSmpl` \ subst ->
332     let
333         (subst', bndrs') = substIds subst ids
334     in
335     seqBndrs bndrs'     `seq`
336     setSubst subst' (thing_inside bndrs')
337
338 seqBndrs [] = ()
339 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
340
341 seqBndr b | isTyVar b = b `seq` ()
342           | otherwise = seqType (idType b)      `seq`
343                         idInfo b                `seq`
344                         ()
345 \end{code}
346
347
348 %************************************************************************
349 %*                                                                      *
350 \subsection{Transform a RHS}
351 %*                                                                      *
352 %************************************************************************
353
354 Try (a) eta expansion
355     (b) type-lambda swizzling
356
357 \begin{code}
358 transformRhs :: InExpr -> SimplM InExpr
359 transformRhs rhs 
360   = tryEtaExpansion body                `thenSmpl` \ body' ->
361     mkRhsTyLam tyvars body'
362   where
363     (tyvars, body) = collectTyBinders rhs
364 \end{code}
365
366
367 %************************************************************************
368 %*                                                                      *
369 \subsection{Local tyvar-lifting}
370 %*                                                                      *
371 %************************************************************************
372
373 mkRhsTyLam tries this transformation, when the big lambda appears as
374 the RHS of a let(rec) binding:
375
376         /\abc -> let(rec) x = e in b
377    ==>
378         let(rec) x' = /\abc -> let x = x' a b c in e
379         in 
380         /\abc -> let x = x' a b c in b
381
382 This is good because it can turn things like:
383
384         let f = /\a -> letrec g = ... g ... in g
385 into
386         letrec g' = /\a -> ... g' a ...
387         in
388         let f = /\ a -> g' a
389
390 which is better.  In effect, it means that big lambdas don't impede
391 let-floating.
392
393 This optimisation is CRUCIAL in eliminating the junk introduced by
394 desugaring mutually recursive definitions.  Don't eliminate it lightly!
395
396 So far as the implemtation is concerned:
397
398         Invariant: go F e = /\tvs -> F e
399         
400         Equalities:
401                 go F (Let x=e in b)
402                 = Let x' = /\tvs -> F e 
403                   in 
404                   go G b
405                 where
406                     G = F . Let x = x' tvs
407         
408                 go F (Letrec xi=ei in b)
409                 = Letrec {xi' = /\tvs -> G ei} 
410                   in
411                   go G b
412                 where
413                   G = F . Let {xi = xi' tvs}
414
415 [May 1999]  If we do this transformation *regardless* then we can
416 end up with some pretty silly stuff.  For example, 
417
418         let 
419             st = /\ s -> let { x1=r1 ; x2=r2 } in ...
420         in ..
421 becomes
422         let y1 = /\s -> r1
423             y2 = /\s -> r2
424             st = /\s -> ...[y1 s/x1, y2 s/x2]
425         in ..
426
427 Unless the "..." is a WHNF there is really no point in doing this.
428 Indeed it can make things worse.  Suppose x1 is used strictly,
429 and is of the form
430
431         x1* = case f y of { (a,b) -> e }
432
433 If we abstract this wrt the tyvar we then can't do the case inline
434 as we would normally do.
435
436
437 \begin{code}
438 mkRhsTyLam tyvars body                  -- Only does something if there's a let
439   | null tyvars || not (worth_it body)  -- inside a type lambda, and a WHNF inside that
440   = returnSmpl (mkLams tyvars body)
441   | otherwise
442   = go (\x -> x) body
443   where
444     worth_it (Let _ e)       = whnf_in_middle e
445     worth_it other           = False
446     whnf_in_middle (Let _ e) = whnf_in_middle e
447     whnf_in_middle e         = exprIsCheap e
448
449     main_tyvar_set = mkVarSet tyvars
450
451     go fn (Let bind@(NonRec var rhs) body) | exprIsTrivial rhs
452       = go (fn . Let bind) body
453
454     go fn (Let bind@(NonRec var rhs) body)
455       = mk_poly tyvars_here var                         `thenSmpl` \ (var', rhs') ->
456         go (fn . Let (mk_silly_bind var rhs')) body     `thenSmpl` \ body' ->
457         returnSmpl (Let (NonRec var' (mkLams tyvars_here (fn rhs))) body')
458       where
459         tyvars_here = tyvars
460                 -- varSetElems (main_tyvar_set `intersectVarSet` tyVarsOfType var_ty)
461                 -- tyvars_here was an attempt to reduce the number of tyvars
462                 -- wrt which the new binding is abstracted.  But the naive
463                 -- approach of abstract wrt the tyvars free in the Id's type
464                 -- fails. Consider:
465                 --      /\ a b -> let t :: (a,b) = (e1, e2)
466                 --                    x :: a     = fst t
467                 --                in ...
468                 -- Here, b isn't free in x's type, but we must nevertheless
469                 -- abstract wrt b as well, because t's type mentions b.
470                 -- Since t is floated too, we'd end up with the bogus:
471                 --      poly_t = /\ a b -> (e1, e2)
472                 --      poly_x = /\ a   -> fst (poly_t a *b*)
473                 -- So for now we adopt the even more naive approach of
474                 -- abstracting wrt *all* the tyvars.  We'll see if that
475                 -- gives rise to problems.   SLPJ June 98
476
477         var_ty = idType var
478
479     go fn (Let (Rec prs) body)
480        = mapAndUnzipSmpl (mk_poly tyvars_here) vars     `thenSmpl` \ (vars', rhss') ->
481          let
482             gn body = fn $ foldr Let body (zipWith mk_silly_bind vars rhss')
483          in
484          go gn body                             `thenSmpl` \ body' ->
485          returnSmpl (Let (Rec (vars' `zip` [mkLams tyvars_here (gn rhs) | rhs <- rhss])) body')
486        where
487          (vars,rhss) = unzip prs
488          tyvars_here = tyvars
489                 -- varSetElems (main_tyvar_set `intersectVarSet` tyVarsOfTypes var_tys)
490                 -- See notes with tyvars_here above
491
492          var_tys     = map idType vars
493
494     go fn body = returnSmpl (mkLams tyvars (fn body))
495
496     mk_poly tyvars_here var
497       = getUniqueSmpl           `thenSmpl` \ uniq ->
498         let
499             poly_name = setNameUnique (idName var) uniq         -- Keep same name
500             poly_ty   = mkForAllTys tyvars_here (idType var)    -- But new type of course
501
502                 -- It's crucial to copy the occInfo of the original var, because
503                 -- we're looking at occurrence-analysed but as yet unsimplified code!
504                 -- In particular, we mustn't lose the loop breakers.
505                 -- 
506                 -- It's even right to retain single-occurrence or dead-var info:
507                 -- Suppose we started with  /\a -> let x = E in B
508                 -- where x occurs once in E. Then we transform to:
509                 --      let x' = /\a -> E in /\a -> let x* = x' a in B
510                 -- where x* has an INLINE prag on it.  Now, once x* is inlined,
511                 -- the occurrences of x' will be just the occurrences originaly
512                 -- pinned on x.
513             poly_info = vanillaIdInfo `setOccInfo` idOccInfo var
514
515             poly_id   = mkId poly_name poly_ty poly_info
516         in
517         returnSmpl (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tyvars_here))
518
519     mk_silly_bind var rhs = NonRec var rhs
520                 -- The Inline note is really important!  If we don't say 
521                 -- INLINE on these silly little bindings then look what happens!
522                 -- Suppose we start with:
523                 --
524                 --      x = let g = /\a -> \x -> f x x
525                 --          in 
526                 --          /\ b -> let g* = g b in E
527                 --
528                 -- Then:        * the binding for g gets floated out
529                 --              * but then it gets inlined into the rhs of g*
530                 --              * then the binding for g* is floated out of the /\b
531                 --              * so we're back to square one
532                 -- The silly binding for g* must be INLINEd, so that
533                 -- we simply substitute for g* throughout.
534 \end{code}
535
536
537 %************************************************************************
538 %*                                                                      *
539 \subsection{Eta expansion}
540 %*                                                                      *
541 %************************************************************************
542
543         Try eta expansion for RHSs
544
545 We go for:
546                 \x1..xn -> N    ==>   \x1..xn y1..ym -> N y1..ym
547         AND             
548                 N E1..En        ==>   let z1=E1 .. zn=En in \y1..ym -> N z1..zn y1..ym
549
550 where (in both cases) N is a NORMAL FORM (i.e. no redexes anywhere)
551 wanting a suitable number of extra args.
552
553 NB: the Ei may have unlifted type, but the simplifier (which is applied
554 to the result) deals OK with this.
555
556 There is no point in looking for a combination of the two, 
557 because that would leave use with some lets sandwiched between lambdas;
558 that's what the final test in the first equation is for.
559
560 \begin{code}
561 tryEtaExpansion :: InExpr -> SimplM InExpr
562 tryEtaExpansion rhs
563   |  not opt_SimplDoLambdaEtaExpansion
564   || exprIsTrivial rhs                          -- Don't eta-expand a trival RHS
565   || null y_tys                                 -- No useful expansion
566   || not (null x_bndrs || and trivial_args)     -- Not (no x-binders or no z-binds)
567   = returnSmpl rhs
568
569   | otherwise   -- Consider eta expansion
570   = newIds SLIT("y") y_tys                                      $ ( \ y_bndrs ->
571     tick (EtaExpansion (head y_bndrs))                          `thenSmpl_`
572     mapAndUnzipSmpl bind_z_arg (args `zip` trivial_args)        `thenSmpl` (\ (maybe_z_binds, z_args) ->
573     returnSmpl (mkLams x_bndrs                          $ 
574                 mkLets (catMaybes maybe_z_binds)        $
575                 mkLams y_bndrs                          $
576                 mkApps (mkApps fun z_args) (map Var y_bndrs))))
577   where
578     (x_bndrs, body) = collectValBinders rhs
579     (fun, args)     = collectArgs body
580     trivial_args    = map exprIsTrivial args
581     fun_arity       = exprEtaExpandArity fun
582
583     bind_z_arg (arg, trivial_arg) 
584         | trivial_arg = returnSmpl (Nothing, arg)
585         | otherwise   = newId SLIT("z") (exprType arg)  $ \ z ->
586                         returnSmpl (Just (NonRec z arg), Var z)
587
588         -- Note: I used to try to avoid the exprType call by using
589         -- the type of the binder.  But this type doesn't necessarily
590         -- belong to the same substitution environment as this rhs;
591         -- and we are going to make extra term binders (y_bndrs) from the type
592         -- which will be processed with the rhs substitution environment.
593         -- This only went wrong in a mind bendingly complicated case.
594     (potential_extra_arg_tys, inner_ty) = splitFunTys (exprType body)
595         
596     y_tys :: [InType]
597     y_tys  = take no_extras_wanted potential_extra_arg_tys
598         
599     no_extras_wanted :: Int
600     no_extras_wanted = 0 `max`
601
602         -- We used to expand the arity to the previous arity fo the
603         -- function; but this is pretty dangerous.  Consdier
604         --      f = \xy -> e
605         -- so that f has arity 2.  Now float something into f's RHS:
606         --      f = let z = BIG in \xy -> e
607         -- The last thing we want to do now is to put some lambdas
608         -- outside, to get
609         --      f = \xy -> let z = BIG in e
610         --
611         -- (bndr_arity - no_of_xs)              `max`
612
613         -- See if the body could obviously do with more args
614         (fun_arity - valArgCount args)
615
616 -- This case is now deal with by exprEtaExpandArity
617         -- Finally, see if it's a state transformer, and xs is non-null
618         -- (so it's also a function not a thunk) in which
619         -- case we eta-expand on principle! This can waste work,
620         -- but usually doesn't.
621         -- I originally checked for a singleton type [ty] in this case
622         -- but then I found a situation in which I had
623         --      \ x -> let {..} in \ s -> f (...) s
624         -- AND f RETURNED A FUNCTION.  That is, 's' wasn't the only
625         -- potential extra arg.
626 --      case (x_bndrs, potential_extra_arg_tys) of
627 --          (_:_, ty:_)  -> case splitTyConApp_maybe ty of
628 --                                Just (tycon,_) | tycon == statePrimTyCon -> 1
629 --                                other                                    -> 0
630 --          other -> 0
631 \end{code}
632
633
634 %************************************************************************
635 %*                                                                      *
636 \subsection{Case absorption and identity-case elimination}
637 %*                                                                      *
638 %************************************************************************
639
640 \begin{code}
641 mkCase :: OutExpr -> OutId -> [OutAlt] -> SimplM OutExpr
642 \end{code}
643
644 @mkCase@ tries the following transformation (if possible):
645
646 case e of b {             ==>   case e of b {
647   p1 -> rhs1                      p1 -> rhs1
648   ...                             ...
649   pm -> rhsm                      pm -> rhsm
650   _  -> case b of b' {            pn -> rhsn[b/b'] {or (alg)  let b=b' in rhsn}
651                                                    {or (prim) case b of b' { _ -> rhsn}}
652               pn -> rhsn          ...
653               ...                 po -> rhso[b/b']
654               po -> rhso          _  -> rhsd[b/b'] {or let b'=b in rhsd}
655               _  -> rhsd
656 }
657
658 which merges two cases in one case when -- the default alternative of
659 the outer case scrutises the same variable as the outer case This
660 transformation is called Case Merging.  It avoids that the same
661 variable is scrutinised multiple times.
662
663 \begin{code}
664 mkCase scrut outer_bndr outer_alts
665   |  opt_SimplCaseMerge
666   && maybeToBool maybe_case_in_default
667      
668   = tick (CaseMerge outer_bndr)         `thenSmpl_`
669     returnSmpl (Case scrut outer_bndr new_alts)
670         -- Warning: don't call mkCase recursively!
671         -- Firstly, there's no point, because inner alts have already had
672         -- mkCase applied to them, so they won't have a case in their default
673         -- Secondly, if you do, you get an infinite loop, because the bindNonRec
674         -- in munge_rhs puts a case into the DEFAULT branch!
675   where
676     new_alts = outer_alts_without_deflt ++ munged_inner_alts
677     maybe_case_in_default = case findDefault outer_alts of
678                                 (outer_alts_without_default,
679                                  Just (Case (Var scrut_var) inner_bndr inner_alts))
680                                  
681                                    | outer_bndr == scrut_var
682                                    -> Just (outer_alts_without_default, inner_bndr, inner_alts)
683                                 other -> Nothing
684
685     Just (outer_alts_without_deflt, inner_bndr, inner_alts) = maybe_case_in_default
686
687                 --  Eliminate any inner alts which are shadowed by the outer ones
688     outer_cons = [con | (con,_,_) <- outer_alts_without_deflt]
689
690     munged_inner_alts = [ (con, args, munge_rhs rhs) 
691                         | (con, args, rhs) <- inner_alts, 
692                            not (con `elem` outer_cons)  -- Eliminate shadowed inner alts
693                         ]
694     munge_rhs rhs = bindNonRec inner_bndr (Var outer_bndr) rhs
695 \end{code}
696
697 Now the identity-case transformation:
698
699         case e of               ===> e
700                 True -> True;
701                 False -> False
702
703 and similar friends.
704
705 \begin{code}
706 mkCase scrut case_bndr alts
707   | all identity_alt alts
708   = tick (CaseIdentity case_bndr)               `thenSmpl_`
709     returnSmpl scrut
710   where
711     identity_alt (DEFAULT, [], Var v)     = v == case_bndr
712     identity_alt (DataAlt con, args, rhs) = cheapEqExpr rhs
713                                                         (mkConApp con (map Type arg_tys ++ map varToCoreExpr args))
714     identity_alt other                    = False
715
716     arg_tys = case splitTyConApp_maybe (idType case_bndr) of
717                 Just (tycon, arg_tys) -> arg_tys
718 \end{code}
719
720 The catch-all case
721
722 \begin{code}
723 mkCase other_scrut case_bndr other_alts
724   = returnSmpl (Case other_scrut case_bndr other_alts)
725 \end{code}
726
727
728 \begin{code}
729 findDefault :: [CoreAlt] -> ([CoreAlt], Maybe CoreExpr)
730 findDefault []                          = ([], Nothing)
731 findDefault ((DEFAULT,args,rhs) : alts) = ASSERT( null alts && null args ) 
732                                           ([], Just rhs)
733 findDefault (alt : alts)                = case findDefault alts of 
734                                             (alts', deflt) -> (alt : alts', deflt)
735
736 findAlt :: AltCon -> [CoreAlt] -> CoreAlt
737 findAlt con alts
738   = go alts
739   where
740     go []           = pprPanic "Missing alternative" (ppr con $$ vcat (map ppr alts))
741     go (alt : alts) | matches alt = alt
742                     | otherwise   = go alts
743
744     matches (DEFAULT, _, _) = True
745     matches (con1, _, _)    = con == con1
746 \end{code}