5c7d33db77dc24631b59dc95d8457eda73117173
[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         countValArgs, countArgs, mkRhsStop, mkStop,
15         getContArgs, interestingCallContext, interestingArg, isStrictType, discardInline
16
17     ) where
18
19 #include "HsVersions.h"
20
21 import CmdLineOpts      ( switchIsOn, SimplifierSwitch(..),
22                           opt_SimplDoLambdaEtaExpansion, opt_SimplCaseMerge, opt_DictsStrict,
23                           opt_UF_UpdateInPlace
24                         )
25 import CoreSyn
26 import CoreUtils        ( exprIsTrivial, cheapEqExpr, exprType, exprIsCheap, exprEtaExpandArity, bindNonRec )
27 import Subst            ( InScopeSet, mkSubst, substBndrs, substBndr, substIds, substExpr )
28 import Id               ( idType, idName, 
29                           idUnfolding, idStrictness,
30                           mkId, idInfo
31                         )
32 import IdInfo           ( StrictnessInfo(..), ArityInfo, atLeastArity, vanillaIdInfo )
33 import Maybes           ( maybeToBool, catMaybes )
34 import Name             ( setNameUnique )
35 import Demand           ( isStrict )
36 import SimplMonad
37 import Type             ( Type, mkForAllTys, seqType, repType,
38                           splitTyConApp_maybe, mkTyVarTys, splitFunTys, 
39                           isDictTy, isDataType, isUnLiftedType,
40                           splitRepFunTys
41                         )
42 import TyCon            ( tyConDataConsIfAvailable )
43 import DataCon          ( dataConRepArity )
44 import VarEnv           ( SubstEnv )
45 import Util             ( lengthExceeds )
46 import Outputable
47 \end{code}
48
49
50 %************************************************************************
51 %*                                                                      *
52 \subsection{The continuation data type}
53 %*                                                                      *
54 %************************************************************************
55
56 \begin{code}
57 data SimplCont          -- Strict contexts
58   = Stop     OutType            -- Type of the result
59              Bool               -- True => This is the RHS of a thunk whose type suggests
60                                 --         that update-in-place would be possible
61                                 --         (This makes the inliner a little keener.)
62
63   | CoerceIt OutType                    -- The To-type, simplified
64              SimplCont
65
66   | InlinePlease                        -- This continuation makes a function very
67              SimplCont                  -- keen to inline itelf
68
69   | ApplyTo  DupFlag 
70              InExpr SubstEnv            -- The argument, as yet unsimplified, 
71              SimplCont                  -- and its subst-env
72
73   | Select   DupFlag 
74              InId [InAlt] SubstEnv      -- The case binder, alts, and subst-env
75              SimplCont
76
77   | ArgOf    DupFlag            -- An arbitrary strict context: the argument 
78                                 --      of a strict function, or a primitive-arg fn
79                                 --      or a PrimOp
80              OutType            -- cont_ty: the type of the expression being sought by the context
81                                 --      f (error "foo") ==> coerce t (error "foo")
82                                 -- when f is strict
83                                 -- We need to know the type t, to which to coerce.
84              (OutExpr -> SimplM OutExprStuff)   -- What to do with the result
85                                 -- The result expression in the OutExprStuff has type cont_ty
86
87 instance Outputable SimplCont where
88   ppr (Stop _ _)                     = ptext SLIT("Stop")
89   ppr (ApplyTo dup arg se cont)      = (ptext SLIT("ApplyTo") <+> ppr dup <+> ppr arg) $$ ppr cont
90   ppr (ArgOf   dup _ _)              = ptext SLIT("ArgOf...") <+> ppr dup
91   ppr (Select dup bndr alts se cont) = (ptext SLIT("Select") <+> ppr dup <+> ppr bndr) $$ 
92                                        (nest 4 (ppr alts)) $$ ppr cont
93   ppr (CoerceIt ty cont)             = (ptext SLIT("CoerceIt") <+> ppr ty) $$ ppr cont
94   ppr (InlinePlease cont)            = ptext SLIT("InlinePlease") $$ ppr cont
95
96 data DupFlag = OkToDup | NoDup
97
98 instance Outputable DupFlag where
99   ppr OkToDup = ptext SLIT("ok")
100   ppr NoDup   = ptext SLIT("nodup")
101
102
103 -------------------
104 mkRhsStop, mkStop :: OutType -> SimplCont
105 mkStop    ty = Stop ty False
106 mkRhsStop ty = Stop ty (canUpdateInPlace ty)
107
108
109 -------------------
110 contIsDupable :: SimplCont -> Bool
111 contIsDupable (Stop _ _)                 = True
112 contIsDupable (ApplyTo  OkToDup _ _ _)   = True
113 contIsDupable (ArgOf    OkToDup _ _)     = True
114 contIsDupable (Select   OkToDup _ _ _ _) = True
115 contIsDupable (CoerceIt _ cont)          = contIsDupable cont
116 contIsDupable (InlinePlease cont)        = contIsDupable cont
117 contIsDupable other                      = False
118
119 -------------------
120 discardInline :: SimplCont -> SimplCont
121 discardInline (InlinePlease cont)  = cont
122 discardInline (ApplyTo d e s cont) = ApplyTo d e s (discardInline cont)
123 discardInline cont                 = cont
124
125 -------------------
126 discardableCont :: SimplCont -> Bool
127 discardableCont (Stop _ _)          = False
128 discardableCont (CoerceIt _ cont)   = discardableCont cont
129 discardableCont (InlinePlease cont) = discardableCont cont
130 discardableCont other               = True
131
132 discardCont :: SimplCont        -- A continuation, expecting
133             -> SimplCont        -- Replace the continuation with a suitable coerce
134 discardCont cont = case cont of
135                      Stop to_ty _ -> cont
136                      other        -> CoerceIt to_ty (mkStop to_ty)
137                  where
138                    to_ty = contResultType cont
139
140 -------------------
141 contResultType :: SimplCont -> OutType
142 contResultType (Stop to_ty _)        = to_ty
143 contResultType (ArgOf _ to_ty _)     = to_ty
144 contResultType (ApplyTo _ _ _ cont)  = contResultType cont
145 contResultType (CoerceIt _ cont)     = contResultType cont
146 contResultType (InlinePlease cont)   = contResultType cont
147 contResultType (Select _ _ _ _ cont) = contResultType cont
148
149 -------------------
150 countValArgs :: SimplCont -> Int
151 countValArgs (ApplyTo _ (Type ty) se cont) = countValArgs cont
152 countValArgs (ApplyTo _ val_arg   se cont) = 1 + countValArgs cont
153 countValArgs other                         = 0
154
155 countArgs :: SimplCont -> Int
156 countArgs (ApplyTo _ arg se cont) = 1 + countArgs cont
157 countArgs other                   = 0
158 \end{code}
159
160
161 \begin{code}
162 getContArgs :: OutId -> SimplCont 
163             -> SimplM ([(InExpr, SubstEnv, Bool)],      -- Arguments; the Bool is true for strict args
164                         SimplCont,                      -- Remaining continuation
165                         Bool)                           -- Whether we came across an InlineCall
166 -- getContArgs id k = (args, k', inl)
167 --      args are the leading ApplyTo items in k
168 --      (i.e. outermost comes first)
169 --      augmented with demand info from the functionn
170 getContArgs fun orig_cont
171   = getSwitchChecker    `thenSmpl` \ chkr ->
172     let
173                 -- Ignore strictness info if the no-case-of-case
174                 -- flag is on.  Strictness changes evaluation order
175                 -- and that can change full laziness
176         stricts | switchIsOn chkr NoCaseOfCase = vanilla_stricts
177                 | otherwise                    = computed_stricts
178     in
179     go [] stricts False orig_cont
180   where
181     ----------------------------
182
183         -- Type argument
184     go acc ss inl (ApplyTo _ arg@(Type _) se cont)
185         = go ((arg,se,False) : acc) ss inl cont
186                 -- NB: don't bother to instantiate the function type
187
188         -- Value argument
189     go acc (s:ss) inl (ApplyTo _ arg se cont)
190         = go ((arg,se,s) : acc) ss inl cont
191
192         -- An Inline continuation
193     go acc ss inl (InlinePlease cont)
194         = go acc ss True cont
195
196         -- We're run out of arguments, or else we've run out of demands
197         -- The latter only happens if the result is guaranteed bottom
198         -- This is the case for
199         --      * case (error "hello") of { ... }
200         --      * (error "Hello") arg
201         --      * f (error "Hello") where f is strict
202         --      etc
203     go acc ss inl cont 
204         | null ss && discardableCont cont = tick BottomFound    `thenSmpl_`
205                                             returnSmpl (reverse acc, discardCont cont, inl)
206         | otherwise                       = returnSmpl (reverse acc, cont,             inl)
207
208     ----------------------------
209     vanilla_stricts, computed_stricts :: [Bool]
210     vanilla_stricts  = repeat False
211     computed_stricts = zipWith (||) fun_stricts arg_stricts
212
213     ----------------------------
214     (val_arg_tys, _) = splitRepFunTys (idType fun)
215     arg_stricts      = map isStrictType val_arg_tys ++ repeat False
216         -- These argument types are used as a cheap and cheerful way to find
217         -- unboxed arguments, which must be strict.  But it's an InType
218         -- and so there might be a type variable where we expect a function
219         -- type (the substitution hasn't happened yet).  And we don't bother
220         -- doing the type applications for a polymorphic function.
221         -- Hence the split*Rep*FunTys
222
223     ----------------------------
224         -- If fun_stricts is finite, it means the function returns bottom
225         -- after that number of value args have been consumed
226         -- Otherwise it's infinite, extended with False
227     fun_stricts
228       = case idStrictness fun of
229           StrictnessInfo demands result_bot 
230                 | not (demands `lengthExceeds` countValArgs orig_cont)
231                 ->      -- Enough args, use the strictness given.
232                         -- For bottoming functions we used to pretend that the arg
233                         -- is lazy, so that we don't treat the arg as an
234                         -- interesting context.  This avoids substituting
235                         -- top-level bindings for (say) strings into 
236                         -- calls to error.  But now we are more careful about
237                         -- inlining lone variables, so its ok (see SimplUtils.analyseCont)
238                    if result_bot then
239                         map isStrict demands            -- Finite => result is bottom
240                    else
241                         map isStrict demands ++ vanilla_stricts
242
243           other -> vanilla_stricts      -- Not enough args, or no strictness
244
245
246 -------------------
247 isStrictType :: Type -> Bool
248         -- isStrictType computes whether an argument (or let RHS) should
249         -- be computed strictly or lazily, based only on its type
250 isStrictType ty
251   | isUnLiftedType ty                               = True
252   | opt_DictsStrict && isDictTy ty && isDataType ty = True
253   | otherwise                                       = False 
254         -- Return true only for dictionary types where the dictionary
255         -- has more than one component (else we risk poking on the component
256         -- of a newtype dictionary)
257
258 -------------------
259 interestingArg :: InScopeSet -> InExpr -> SubstEnv -> Bool
260         -- An argument is interesting if it has *some* structure
261         -- We are here trying to avoid unfolding a function that
262         -- is applied only to variables that have no unfolding
263         -- (i.e. they are probably lambda bound): f x y z
264         -- There is little point in inlining f here.
265 interestingArg in_scope arg subst
266   = analyse (substExpr (mkSubst in_scope subst) arg)
267         -- 'analyse' only looks at the top part of the result
268         -- and substExpr is lazy, so this isn't nearly as brutal
269         -- as it looks.
270   where
271     analyse (Var v)           = hasSomeUnfolding (idUnfolding v)
272                                 -- Was: isValueUnfolding (idUnfolding v')
273                                 -- But that seems over-pessimistic
274     analyse (Type _)          = False
275     analyse (App fn (Type _)) = analyse fn
276     analyse (Note _ a)        = analyse a
277     analyse other             = True
278         -- Consider     let x = 3 in f x
279         -- The substitution will contain (x -> ContEx 3), and we want to
280         -- to say that x is an interesting argument.
281         -- But consider also (\x. f x y) y
282         -- The substitution will contain (x -> ContEx y), and we want to say
283         -- that x is not interesting (assuming y has no unfolding)
284 \end{code}
285
286 Comment about interestingCallContext
287 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
288 We want to avoid inlining an expression where there can't possibly be
289 any gain, such as in an argument position.  Hence, if the continuation
290 is interesting (eg. a case scrutinee, application etc.) then we
291 inline, otherwise we don't.  
292
293 Previously some_benefit used to return True only if the variable was
294 applied to some value arguments.  This didn't work:
295
296         let x = _coerce_ (T Int) Int (I# 3) in
297         case _coerce_ Int (T Int) x of
298                 I# y -> ....
299
300 we want to inline x, but can't see that it's a constructor in a case
301 scrutinee position, and some_benefit is False.
302
303 Another example:
304
305 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
306
307 ....  case dMonadST _@_ x0 of (a,b,c) -> ....
308
309 we'd really like to inline dMonadST here, but we *don't* want to
310 inline if the case expression is just
311
312         case x of y { DEFAULT -> ... }
313
314 since we can just eliminate this case instead (x is in WHNF).  Similar
315 applies when x is bound to a lambda expression.  Hence
316 contIsInteresting looks for case expressions with just a single
317 default case.
318
319 \begin{code}
320 interestingCallContext :: Bool          -- False <=> no args at all
321                        -> Bool          -- False <=> no value args
322                        -> SimplCont -> Bool
323         -- The "lone-variable" case is important.  I spent ages
324         -- messing about with unsatisfactory varaints, but this is nice.
325         -- The idea is that if a variable appear all alone
326         --      as an arg of lazy fn, or rhs    Stop
327         --      as scrutinee of a case          Select
328         --      as arg of a strict fn           ArgOf
329         -- then we should not inline it (unless there is some other reason,
330         -- e.g. is is the sole occurrence).  We achieve this by making
331         -- interestingCallContext return False for a lone variable.
332         --
333         -- Why?  At least in the case-scrutinee situation, turning
334         --      let x = (a,b) in case x of y -> ...
335         -- into
336         --      let x = (a,b) in case (a,b) of y -> ...
337         -- and thence to 
338         --      let x = (a,b) in let y = (a,b) in ...
339         -- is bad if the binding for x will remain.
340         --
341         -- Another example: I discovered that strings
342         -- were getting inlined straight back into applications of 'error'
343         -- because the latter is strict.
344         --      s = "foo"
345         --      f = \x -> ...(error s)...
346
347         -- Fundamentally such contexts should not ecourage inlining becuase
348         -- the context can ``see'' the unfolding of the variable (e.g. case or a RULE)
349         -- so there's no gain.
350         --
351         -- However, even a type application or coercion isn't a lone variable.
352         -- Consider
353         --      case $fMonadST @ RealWorld of { :DMonad a b c -> c }
354         -- We had better inline that sucker!  The case won't see through it.
355         --
356         -- For now, I'm treating treating a variable applied to types 
357         -- in a *lazy* context "lone". The motivating example was
358         --      f = /\a. \x. BIG
359         --      g = /\a. \y.  h (f a)
360         -- There's no advantage in inlining f here, and perhaps
361         -- a significant disadvantage.  Hence some_val_args in the Stop case
362
363 interestingCallContext some_args some_val_args cont
364   = interesting cont
365   where
366     interesting (InlinePlease _)       = True
367     interesting (Select _ _ _ _ _)     = some_args
368     interesting (ApplyTo _ _ _ _)      = some_args      -- Can happen if we have (coerce t (f x)) y
369     interesting (ArgOf _ _ _)          = some_val_args
370     interesting (Stop ty upd_in_place) = some_val_args && upd_in_place
371     interesting (CoerceIt _ cont)      = interesting cont
372         -- If this call is the arg of a strict function, the context
373         -- is a bit interesting.  If we inline here, we may get useful
374         -- evaluation information to avoid repeated evals: e.g.
375         --      x + (y * z)
376         -- Here the contIsInteresting makes the '*' keener to inline,
377         -- which in turn exposes a constructor which makes the '+' inline.
378         -- Assuming that +,* aren't small enough to inline regardless.
379         --
380         -- It's also very important to inline in a strict context for things
381         -- like
382         --              foldr k z (f x)
383         -- Here, the context of (f x) is strict, and if f's unfolding is
384         -- a build it's *great* to inline it here.  So we must ensure that
385         -- the context for (f x) is not totally uninteresting.
386
387
388 -------------------
389 canUpdateInPlace :: Type -> Bool
390 -- Consider   let x = <wurble> in ...
391 -- If <wurble> returns an explicit constructor, we might be able
392 -- to do update in place.  So we treat even a thunk RHS context
393 -- as interesting if update in place is possible.  We approximate
394 -- this by seeing if the type has a single constructor with a
395 -- small arity.  But arity zero isn't good -- we share the single copy
396 -- for that case, so no point in sharing.
397
398 -- Note the repType: we want to look through newtypes for this purpose
399
400 canUpdateInPlace ty 
401   | not opt_UF_UpdateInPlace = False
402   | otherwise
403   = case splitTyConApp_maybe (repType ty) of {
404                         Nothing         -> False ;
405                         Just (tycon, _) -> 
406
407                       case tyConDataConsIfAvailable tycon of
408                         [dc]  -> arity == 1 || arity == 2
409                               where
410                                  arity = dataConRepArity dc
411                         other -> False
412                       }
413 \end{code}
414
415
416
417 %************************************************************************
418 %*                                                                      *
419 \section{Dealing with a single binder}
420 %*                                                                      *
421 %************************************************************************
422
423 \begin{code}
424 simplBinders :: [InBinder] -> ([OutBinder] -> SimplM a) -> SimplM a
425 simplBinders bndrs thing_inside
426   = getSubst            `thenSmpl` \ subst ->
427     let
428         (subst', bndrs') = substBndrs subst bndrs
429     in
430     seqBndrs bndrs'     `seq`
431     setSubst subst' (thing_inside bndrs')
432
433 simplBinder :: InBinder -> (OutBinder -> SimplM a) -> SimplM a
434 simplBinder bndr thing_inside
435   = getSubst            `thenSmpl` \ subst ->
436     let
437         (subst', bndr') = substBndr subst bndr
438     in
439     seqBndr bndr'       `seq`
440     setSubst subst' (thing_inside bndr')
441
442
443 -- Same semantics as simplBinders, but a little less 
444 -- plumbing and hence a little more efficient.
445 -- Maybe not worth the candle?
446 simplIds :: [InBinder] -> ([OutBinder] -> SimplM a) -> SimplM a
447 simplIds ids thing_inside
448   = getSubst            `thenSmpl` \ subst ->
449     let
450         (subst', bndrs') = substIds subst ids
451     in
452     seqBndrs bndrs'     `seq`
453     setSubst subst' (thing_inside bndrs')
454
455 seqBndrs [] = ()
456 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
457
458 seqBndr b | isTyVar b = b `seq` ()
459           | otherwise = seqType (idType b)      `seq`
460                         idInfo b                `seq`
461                         ()
462 \end{code}
463
464
465 %************************************************************************
466 %*                                                                      *
467 \subsection{Transform a RHS}
468 %*                                                                      *
469 %************************************************************************
470
471 Try (a) eta expansion
472     (b) type-lambda swizzling
473
474 \begin{code}
475 transformRhs :: OutExpr 
476              -> (ArityInfo -> OutExpr -> SimplM (OutStuff a))
477              -> SimplM (OutStuff a)
478
479 transformRhs rhs thing_inside 
480   = tryRhsTyLam rhs                     $ \ rhs1 ->
481     tryEtaExpansion rhs1 thing_inside
482 \end{code}
483
484
485 %************************************************************************
486 %*                                                                      *
487 \subsection{Local tyvar-lifting}
488 %*                                                                      *
489 %************************************************************************
490
491 mkRhsTyLam tries this transformation, when the big lambda appears as
492 the RHS of a let(rec) binding:
493
494         /\abc -> let(rec) x = e in b
495    ==>
496         let(rec) x' = /\abc -> let x = x' a b c in e
497         in 
498         /\abc -> let x = x' a b c in b
499
500 This is good because it can turn things like:
501
502         let f = /\a -> letrec g = ... g ... in g
503 into
504         letrec g' = /\a -> ... g' a ...
505         in
506         let f = /\ a -> g' a
507
508 which is better.  In effect, it means that big lambdas don't impede
509 let-floating.
510
511 This optimisation is CRUCIAL in eliminating the junk introduced by
512 desugaring mutually recursive definitions.  Don't eliminate it lightly!
513
514 So far as the implementation is concerned:
515
516         Invariant: go F e = /\tvs -> F e
517         
518         Equalities:
519                 go F (Let x=e in b)
520                 = Let x' = /\tvs -> F e 
521                   in 
522                   go G b
523                 where
524                     G = F . Let x = x' tvs
525         
526                 go F (Letrec xi=ei in b)
527                 = Letrec {xi' = /\tvs -> G ei} 
528                   in
529                   go G b
530                 where
531                   G = F . Let {xi = xi' tvs}
532
533 [May 1999]  If we do this transformation *regardless* then we can
534 end up with some pretty silly stuff.  For example, 
535
536         let 
537             st = /\ s -> let { x1=r1 ; x2=r2 } in ...
538         in ..
539 becomes
540         let y1 = /\s -> r1
541             y2 = /\s -> r2
542             st = /\s -> ...[y1 s/x1, y2 s/x2]
543         in ..
544
545 Unless the "..." is a WHNF there is really no point in doing this.
546 Indeed it can make things worse.  Suppose x1 is used strictly,
547 and is of the form
548
549         x1* = case f y of { (a,b) -> e }
550
551 If we abstract this wrt the tyvar we then can't do the case inline
552 as we would normally do.
553
554
555 \begin{code}
556 tryRhsTyLam rhs thing_inside            -- Only does something if there's a let
557   | null tyvars || not (worth_it body)  -- inside a type lambda, and a WHNF inside that
558   = thing_inside rhs
559   | otherwise
560   = go (\x -> x) body           $ \ body' ->
561     thing_inside (mkLams tyvars body')
562
563   where
564     (tyvars, body) = collectTyBinders rhs
565
566     worth_it (Let _ e)       = whnf_in_middle e
567     worth_it other           = False
568     whnf_in_middle (Let _ e) = whnf_in_middle e
569     whnf_in_middle e         = exprIsCheap e
570
571
572     go fn (Let bind@(NonRec var rhs) body) thing_inside
573       | exprIsTrivial rhs
574       = go (fn . Let bind) body thing_inside
575
576     go fn (Let bind@(NonRec var rhs) body) thing_inside
577       = mk_poly tyvars_here var                                         `thenSmpl` \ (var', rhs') ->
578         addAuxiliaryBind (NonRec var' (mkLams tyvars_here (fn rhs)))    $
579         go (fn . Let (mk_silly_bind var rhs')) body thing_inside
580
581       where
582         tyvars_here = tyvars
583                 --      main_tyvar_set = mkVarSet tyvars
584                 --      var_ty = idType var
585                 -- varSetElems (main_tyvar_set `intersectVarSet` tyVarsOfType var_ty)
586                 -- tyvars_here was an attempt to reduce the number of tyvars
587                 -- wrt which the new binding is abstracted.  But the naive
588                 -- approach of abstract wrt the tyvars free in the Id's type
589                 -- fails. Consider:
590                 --      /\ a b -> let t :: (a,b) = (e1, e2)
591                 --                    x :: a     = fst t
592                 --                in ...
593                 -- Here, b isn't free in x's type, but we must nevertheless
594                 -- abstract wrt b as well, because t's type mentions b.
595                 -- Since t is floated too, we'd end up with the bogus:
596                 --      poly_t = /\ a b -> (e1, e2)
597                 --      poly_x = /\ a   -> fst (poly_t a *b*)
598                 -- So for now we adopt the even more naive approach of
599                 -- abstracting wrt *all* the tyvars.  We'll see if that
600                 -- gives rise to problems.   SLPJ June 98
601
602     go fn (Let (Rec prs) body) thing_inside
603        = mapAndUnzipSmpl (mk_poly tyvars_here) vars     `thenSmpl` \ (vars', rhss') ->
604          let
605             gn body = fn (foldr Let body (zipWith mk_silly_bind vars rhss'))
606          in
607          addAuxiliaryBind (Rec (vars' `zip` [mkLams tyvars_here (gn rhs) | rhs <- rhss]))       $
608          go gn body thing_inside
609        where
610          (vars,rhss) = unzip prs
611          tyvars_here = tyvars
612                 -- varSetElems (main_tyvar_set `intersectVarSet` tyVarsOfTypes var_tys)
613                 --       var_tys     = map idType vars
614                 -- See notes with tyvars_here above
615
616
617     go fn body thing_inside = thing_inside (fn body)
618
619     mk_poly tyvars_here var
620       = getUniqueSmpl           `thenSmpl` \ uniq ->
621         let
622             poly_name = setNameUnique (idName var) uniq         -- Keep same name
623             poly_ty   = mkForAllTys tyvars_here (idType var)    -- But new type of course
624             poly_id   = mkId poly_name poly_ty vanillaIdInfo
625
626                 -- In the olden days, it was crucial to copy the occInfo of the original var, 
627                 -- because we were looking at occurrence-analysed but as yet unsimplified code!
628                 -- In particular, we mustn't lose the loop breakers.  BUT NOW we are looking
629                 -- at already simplified code, so it doesn't matter
630                 -- 
631                 -- It's even right to retain single-occurrence or dead-var info:
632                 -- Suppose we started with  /\a -> let x = E in B
633                 -- where x occurs once in B. Then we transform to:
634                 --      let x' = /\a -> E in /\a -> let x* = x' a in B
635                 -- where x* has an INLINE prag on it.  Now, once x* is inlined,
636                 -- the occurrences of x' will be just the occurrences originally
637                 -- pinned on x.
638         in
639         returnSmpl (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tyvars_here))
640
641     mk_silly_bind var rhs = NonRec var (Note InlineMe rhs)
642                 -- Suppose we start with:
643                 --
644                 --      x = /\ a -> let g = G in E
645                 --
646                 -- Then we'll float to get
647                 --
648                 --      x = let poly_g = /\ a -> G
649                 --          in /\ a -> let g = poly_g a in E
650                 --
651                 -- But now the occurrence analyser will see just one occurrence
652                 -- of poly_g, not inside a lambda, so the simplifier will
653                 -- PreInlineUnconditionally poly_g back into g!  Badk to square 1!
654                 -- (I used to think that the "don't inline lone occurrences" stuff
655                 --  would stop this happening, but since it's the *only* occurrence,
656                 --  PreInlineUnconditionally kicks in first!)
657                 --
658                 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
659                 --           to appear many times.  (NB: mkInlineMe eliminates
660                 --           such notes on trivial RHSs, so do it manually.)
661 \end{code}
662
663
664 %************************************************************************
665 %*                                                                      *
666 \subsection{Eta expansion}
667 %*                                                                      *
668 %************************************************************************
669
670         Try eta expansion for RHSs
671
672 We go for:
673    Case 1    f = \x1..xn -> N  ==>   f = \x1..xn y1..ym -> N y1..ym
674                  (n >= 0)
675      OR         
676    Case 2    f = N E1..En      ==>   z1=E1
677                  (n > 0)                 .. 
678                                      zn=En
679                                      f = \y1..ym -> N z1..zn y1..ym
680
681 where (in both cases) 
682
683         * The xi can include type variables
684
685         * The yi are all value variables
686
687         * N is a NORMAL FORM (i.e. no redexes anywhere)
688           wanting a suitable number of extra args.
689
690         * the Ei must not have unlifted type
691
692 There is no point in looking for a combination of the two, because
693 that would leave use with some lets sandwiched between lambdas; that's
694 what the final test in the first equation is for.
695
696 \begin{code}
697 tryEtaExpansion :: OutExpr 
698                 -> (ArityInfo -> OutExpr -> SimplM (OutStuff a))
699                 -> SimplM (OutStuff a)
700 tryEtaExpansion rhs thing_inside
701   |  not opt_SimplDoLambdaEtaExpansion
702   || null y_tys                         -- No useful expansion
703   || not (is_case1 || is_case2)         -- Neither case matches
704   = thing_inside final_arity rhs        -- So, no eta expansion, but
705                                         -- return a good arity
706
707   | is_case1
708   = make_y_bndrs                        $ \ y_bndrs ->
709     thing_inside final_arity
710                  (mkLams x_bndrs $ mkLams y_bndrs $
711                   mkApps body (map Var y_bndrs))
712
713   | otherwise   -- Must be case 2
714   = mapAndUnzipSmpl bind_z_arg arg_infos                `thenSmpl` \ (maybe_z_binds, z_args) ->
715     addAuxiliaryBinds (catMaybes maybe_z_binds)         $
716     make_y_bndrs                                        $  \ y_bndrs ->
717     thing_inside final_arity
718                  (mkLams y_bndrs $
719                   mkApps (mkApps fun z_args) (map Var y_bndrs))
720   where
721     all_trivial_args = all is_trivial arg_infos
722     is_case1         = all_trivial_args
723     is_case2         = null x_bndrs && not (any unlifted_non_trivial arg_infos)
724
725     (x_bndrs, body)  = collectBinders rhs       -- NB: x_bndrs can include type variables
726     x_arity          = valBndrCount x_bndrs
727
728     (fun, args)      = collectArgs body
729     arg_infos        = [(arg, exprType arg, exprIsTrivial arg) | arg <- args]
730
731     is_trivial           (_, _,  triv) = triv
732     unlifted_non_trivial (_, ty, triv) = not triv && isUnLiftedType ty
733
734     fun_arity        = exprEtaExpandArity fun
735
736     final_arity | all_trivial_args = atLeastArity (x_arity + extra_args_wanted)
737                 | otherwise        = atLeastArity x_arity
738         -- Arity can be more than the number of lambdas
739         -- because of coerces. E.g.  \x -> coerce t (\y -> e) 
740         -- will have arity at least 2
741         -- The worker/wrapper pass will bring the coerce out to the top
742
743     bind_z_arg (arg, arg_ty, trivial_arg) 
744         | trivial_arg = returnSmpl (Nothing, arg)
745         | otherwise   = newId SLIT("z") arg_ty  $ \ z ->
746                         returnSmpl (Just (NonRec z arg), Var z)
747
748     make_y_bndrs thing_inside 
749         = ASSERT( not (exprIsTrivial rhs) )
750           newIds SLIT("y") y_tys                        $ \ y_bndrs ->
751           tick (EtaExpansion (head y_bndrs))            `thenSmpl_`
752           thing_inside y_bndrs
753
754     (potential_extra_arg_tys, _) = splitFunTys (exprType body)
755         
756     y_tys :: [InType]
757     y_tys  = take extra_args_wanted potential_extra_arg_tys
758         
759     extra_args_wanted :: Int    -- Number of extra args we want
760     extra_args_wanted = 0 `max` (fun_arity - valArgCount args)
761
762         -- We used to expand the arity to the previous arity fo the
763         -- function; but this is pretty dangerous.  Consdier
764         --      f = \xy -> e
765         -- so that f has arity 2.  Now float something into f's RHS:
766         --      f = let z = BIG in \xy -> e
767         -- The last thing we want to do now is to put some lambdas
768         -- outside, to get
769         --      f = \xy -> let z = BIG in e
770         --
771         -- (bndr_arity - no_of_xs)              `max`
772 \end{code}
773
774
775 %************************************************************************
776 %*                                                                      *
777 \subsection{Case absorption and identity-case elimination}
778 %*                                                                      *
779 %************************************************************************
780
781 \begin{code}
782 mkCase :: OutExpr -> OutId -> [OutAlt] -> SimplM OutExpr
783 \end{code}
784
785 @mkCase@ tries the following transformation (if possible):
786
787 case e of b {             ==>   case e of b {
788   p1 -> rhs1                      p1 -> rhs1
789   ...                             ...
790   pm -> rhsm                      pm -> rhsm
791   _  -> case b of b' {            pn -> rhsn[b/b'] {or (alg)  let b=b' in rhsn}
792                                                    {or (prim) case b of b' { _ -> rhsn}}
793               pn -> rhsn          ...
794               ...                 po -> rhso[b/b']
795               po -> rhso          _  -> rhsd[b/b'] {or let b'=b in rhsd}
796               _  -> rhsd
797 }
798
799 which merges two cases in one case when -- the default alternative of
800 the outer case scrutises the same variable as the outer case This
801 transformation is called Case Merging.  It avoids that the same
802 variable is scrutinised multiple times.
803
804 \begin{code}
805 mkCase scrut outer_bndr outer_alts
806   |  opt_SimplCaseMerge
807   && maybeToBool maybe_case_in_default
808      
809   = tick (CaseMerge outer_bndr)         `thenSmpl_`
810     returnSmpl (Case scrut outer_bndr new_alts)
811         -- Warning: don't call mkCase recursively!
812         -- Firstly, there's no point, because inner alts have already had
813         -- mkCase applied to them, so they won't have a case in their default
814         -- Secondly, if you do, you get an infinite loop, because the bindNonRec
815         -- in munge_rhs puts a case into the DEFAULT branch!
816   where
817     new_alts = outer_alts_without_deflt ++ munged_inner_alts
818     maybe_case_in_default = case findDefault outer_alts of
819                                 (outer_alts_without_default,
820                                  Just (Case (Var scrut_var) inner_bndr inner_alts))
821                                  
822                                    | outer_bndr == scrut_var
823                                    -> Just (outer_alts_without_default, inner_bndr, inner_alts)
824                                 other -> Nothing
825
826     Just (outer_alts_without_deflt, inner_bndr, inner_alts) = maybe_case_in_default
827
828                 --  Eliminate any inner alts which are shadowed by the outer ones
829     outer_cons = [con | (con,_,_) <- outer_alts_without_deflt]
830
831     munged_inner_alts = [ (con, args, munge_rhs rhs) 
832                         | (con, args, rhs) <- inner_alts, 
833                            not (con `elem` outer_cons)  -- Eliminate shadowed inner alts
834                         ]
835     munge_rhs rhs = bindNonRec inner_bndr (Var outer_bndr) rhs
836 \end{code}
837
838 Now the identity-case transformation:
839
840         case e of               ===> e
841                 True -> True;
842                 False -> False
843
844 and similar friends.
845
846 \begin{code}
847 mkCase scrut case_bndr alts
848   | all identity_alt alts
849   = tick (CaseIdentity case_bndr)               `thenSmpl_`
850     returnSmpl scrut
851   where
852     identity_alt (DEFAULT, [], Var v)     = v == case_bndr
853     identity_alt (DataAlt con, args, rhs) = cheapEqExpr rhs
854                                                         (mkConApp con (map Type arg_tys ++ map varToCoreExpr args))
855     identity_alt other                    = False
856
857     arg_tys = case splitTyConApp_maybe (idType case_bndr) of
858                 Just (tycon, arg_tys) -> arg_tys
859 \end{code}
860
861 The catch-all case
862
863 \begin{code}
864 mkCase other_scrut case_bndr other_alts
865   = returnSmpl (Case other_scrut case_bndr other_alts)
866 \end{code}
867
868
869 \begin{code}
870 findDefault :: [CoreAlt] -> ([CoreAlt], Maybe CoreExpr)
871 findDefault []                          = ([], Nothing)
872 findDefault ((DEFAULT,args,rhs) : alts) = ASSERT( null alts && null args ) 
873                                           ([], Just rhs)
874 findDefault (alt : alts)                = case findDefault alts of 
875                                             (alts', deflt) -> (alt : alts', deflt)
876
877 findAlt :: AltCon -> [CoreAlt] -> CoreAlt
878 findAlt con alts
879   = go alts
880   where
881     go []           = pprPanic "Missing alternative" (ppr con $$ vcat (map ppr alts))
882     go (alt : alts) | matches alt = alt
883                     | otherwise   = go alts
884
885     matches (DEFAULT, _, _) = True
886     matches (con1, _, _)    = con == con1
887 \end{code}