[project @ 2001-12-14 17:24:03 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, simplRecBndrs, 
9         simplLetBndr, simplLamBndrs, 
10         newId, mkLam, mkCase,
11
12         -- The continuation type
13         SimplCont(..), DupFlag(..), LetRhsFlag(..), 
14         contIsDupable, contResultType,
15         countValArgs, countArgs, pushContArgs,
16         mkBoringStop, mkStop, contIsRhs, contIsRhsOrArg,
17         getContArgs, interestingCallContext, interestingArg, isStrictType
18
19     ) where
20
21 #include "HsVersions.h"
22
23 import CmdLineOpts      ( SimplifierSwitch(..),
24                           opt_SimplDoLambdaEtaExpansion, opt_SimplDoEtaReduction,
25                           opt_SimplCaseMerge, opt_UF_UpdateInPlace
26                         )
27 import CoreSyn
28 import CoreUtils        ( cheapEqExpr, exprType, 
29                           etaExpand, exprEtaExpandArity, bindNonRec, mkCoerce,
30                           findDefault, exprOkForSpeculation, exprIsValue
31                         )
32 import qualified Subst  ( simplBndrs, simplBndr, simplLetId, simplLamBndr )
33 import Id               ( Id, idType, idInfo, 
34                           mkSysLocal, isDeadBinder, idNewDemandInfo,
35                           idUnfolding, idNewStrictness
36                         )
37 import NewDemand        ( isStrictDmd, isBotRes, splitStrictSig )
38 import SimplMonad
39 import Type             ( Type, seqType, splitRepFunTys, isStrictType,
40                           splitTyConApp_maybe, tyConAppArgs, mkTyVarTys
41                         )
42 import TcType           ( isDictTy )
43 import OccName          ( UserFS )
44 import TyCon            ( tyConDataConsIfAvailable, isAlgTyCon, isNewTyCon )
45 import DataCon          ( dataConRepArity, dataConSig, dataConArgTys )
46 import Var              ( mkSysTyVar, tyVarKind )
47 import Util             ( lengthExceeds, 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              LetRhsFlag
62              Bool               -- True <=> This is the RHS of a thunk whose type suggests
63                                 --          that update-in-place would be possible
64                                 --          (This makes the inliner a little keener.)
65
66   | CoerceIt OutType                    -- The To-type, simplified
67              SimplCont
68
69   | InlinePlease                        -- This continuation makes a function very
70              SimplCont                  -- keen to inline itelf
71
72   | ApplyTo  DupFlag 
73              InExpr SimplEnv            -- The argument, as yet unsimplified, 
74              SimplCont                  -- and its environment
75
76   | Select   DupFlag 
77              InId [InAlt] SimplEnv      -- The case binder, alts, and subst-env
78              SimplCont
79
80   | ArgOf    LetRhsFlag         -- An arbitrary strict context: the argument 
81                                 --      of a strict function, or a primitive-arg fn
82                                 --      or a PrimOp
83                                 -- No DupFlag because we never duplicate it
84              OutType            -- arg_ty: type of the argument itself
85              OutType            -- cont_ty: the type of the expression being sought by the context
86                                 --      f (error "foo") ==> coerce t (error "foo")
87                                 -- when f is strict
88                                 -- We need to know the type t, to which to coerce.
89
90              (SimplEnv -> OutExpr -> SimplM FloatsWithExpr)     -- What to do with the result
91                                 -- The result expression in the OutExprStuff has type cont_ty
92
93 data LetRhsFlag = AnArg         -- It's just an argument not a let RHS
94                 | AnRhs         -- It's the RHS of a let (so please float lets out of big lambdas)
95
96 instance Outputable LetRhsFlag where
97   ppr AnArg = ptext SLIT("arg")
98   ppr AnRhs = ptext SLIT("rhs")
99
100 instance Outputable SimplCont where
101   ppr (Stop _ is_rhs _)              = ptext SLIT("Stop") <> brackets (ppr is_rhs)
102   ppr (ApplyTo dup arg se cont)      = (ptext SLIT("ApplyTo") <+> ppr dup <+> ppr arg) $$ ppr cont
103   ppr (ArgOf _ _ _ _)                = ptext SLIT("ArgOf...")
104   ppr (Select dup bndr alts se cont) = (ptext SLIT("Select") <+> ppr dup <+> ppr bndr) $$ 
105                                        (nest 4 (ppr alts)) $$ ppr cont
106   ppr (CoerceIt ty cont)             = (ptext SLIT("CoerceIt") <+> ppr ty) $$ ppr cont
107   ppr (InlinePlease cont)            = ptext SLIT("InlinePlease") $$ ppr cont
108
109 data DupFlag = OkToDup | NoDup
110
111 instance Outputable DupFlag where
112   ppr OkToDup = ptext SLIT("ok")
113   ppr NoDup   = ptext SLIT("nodup")
114
115
116 -------------------
117 mkBoringStop :: OutType -> SimplCont
118 mkBoringStop ty = Stop ty AnArg (canUpdateInPlace ty)
119
120 mkStop :: OutType -> LetRhsFlag -> SimplCont
121 mkStop ty is_rhs = Stop ty is_rhs (canUpdateInPlace ty)
122
123 contIsRhs :: SimplCont -> Bool
124 contIsRhs (Stop _ AnRhs _)    = True
125 contIsRhs (ArgOf AnRhs _ _ _) = True
126 contIsRhs other               = False
127
128 contIsRhsOrArg (Stop _ _ _)    = True
129 contIsRhsOrArg (ArgOf _ _ _ _) = True
130 contIsRhsOrArg other           = False
131
132 -------------------
133 contIsDupable :: SimplCont -> Bool
134 contIsDupable (Stop _ _ _)               = True
135 contIsDupable (ApplyTo  OkToDup _ _ _)   = True
136 contIsDupable (Select   OkToDup _ _ _ _) = True
137 contIsDupable (CoerceIt _ cont)          = contIsDupable cont
138 contIsDupable (InlinePlease cont)        = contIsDupable cont
139 contIsDupable other                      = False
140
141 -------------------
142 discardableCont :: SimplCont -> Bool
143 discardableCont (Stop _ _ _)        = False
144 discardableCont (CoerceIt _ cont)   = discardableCont cont
145 discardableCont (InlinePlease cont) = discardableCont cont
146 discardableCont other               = True
147
148 discardCont :: SimplCont        -- A continuation, expecting
149             -> SimplCont        -- Replace the continuation with a suitable coerce
150 discardCont cont = case cont of
151                      Stop to_ty is_rhs _ -> cont
152                      other               -> CoerceIt to_ty (mkBoringStop to_ty)
153                  where
154                    to_ty = contResultType cont
155
156 -------------------
157 contResultType :: SimplCont -> OutType
158 contResultType (Stop to_ty _ _)      = to_ty
159 contResultType (ArgOf _ _ to_ty _)   = to_ty
160 contResultType (ApplyTo _ _ _ cont)  = contResultType cont
161 contResultType (CoerceIt _ cont)     = contResultType cont
162 contResultType (InlinePlease cont)   = contResultType cont
163 contResultType (Select _ _ _ _ cont) = contResultType cont
164
165 -------------------
166 countValArgs :: SimplCont -> Int
167 countValArgs (ApplyTo _ (Type ty) se cont) = countValArgs cont
168 countValArgs (ApplyTo _ val_arg   se cont) = 1 + countValArgs cont
169 countValArgs other                         = 0
170
171 countArgs :: SimplCont -> Int
172 countArgs (ApplyTo _ arg se cont) = 1 + countArgs cont
173 countArgs other                   = 0
174
175 -------------------
176 pushContArgs :: SimplEnv -> [OutArg] -> SimplCont -> SimplCont
177 -- Pushes args with the specified environment
178 pushContArgs env []           cont = cont
179 pushContArgs env (arg : args) cont = ApplyTo NoDup arg env (pushContArgs env args cont)
180 \end{code}
181
182
183 \begin{code}
184 getContArgs :: SwitchChecker
185             -> OutId -> SimplCont 
186             -> ([(InExpr, SimplEnv, Bool)],     -- Arguments; the Bool is true for strict args
187                 SimplCont,                      -- Remaining continuation
188                 Bool)                           -- Whether we came across an InlineCall
189 -- getContArgs id k = (args, k', inl)
190 --      args are the leading ApplyTo items in k
191 --      (i.e. outermost comes first)
192 --      augmented with demand info from the functionn
193 getContArgs chkr fun orig_cont
194   = let
195                 -- Ignore strictness info if the no-case-of-case
196                 -- flag is on.  Strictness changes evaluation order
197                 -- and that can change full laziness
198         stricts | switchIsOn chkr NoCaseOfCase = vanilla_stricts
199                 | otherwise                    = computed_stricts
200     in
201     go [] stricts False orig_cont
202   where
203     ----------------------------
204
205         -- Type argument
206     go acc ss inl (ApplyTo _ arg@(Type _) se cont)
207         = go ((arg,se,False) : acc) ss inl cont
208                 -- NB: don't bother to instantiate the function type
209
210         -- Value argument
211     go acc (s:ss) inl (ApplyTo _ arg se cont)
212         = go ((arg,se,s) : acc) ss inl cont
213
214         -- An Inline continuation
215     go acc ss inl (InlinePlease cont)
216         = go acc ss True cont
217
218         -- We're run out of arguments, or else we've run out of demands
219         -- The latter only happens if the result is guaranteed bottom
220         -- This is the case for
221         --      * case (error "hello") of { ... }
222         --      * (error "Hello") arg
223         --      * f (error "Hello") where f is strict
224         --      etc
225     go acc ss inl cont 
226         | null ss && discardableCont cont = (reverse acc, discardCont cont, inl)
227         | otherwise                       = (reverse acc, cont,             inl)
228
229     ----------------------------
230     vanilla_stricts, computed_stricts :: [Bool]
231     vanilla_stricts  = repeat False
232     computed_stricts = zipWith (||) fun_stricts arg_stricts
233
234     ----------------------------
235     (val_arg_tys, _) = splitRepFunTys (idType fun)
236     arg_stricts      = map isStrictType val_arg_tys ++ repeat False
237         -- These argument types are used as a cheap and cheerful way to find
238         -- unboxed arguments, which must be strict.  But it's an InType
239         -- and so there might be a type variable where we expect a function
240         -- type (the substitution hasn't happened yet).  And we don't bother
241         -- doing the type applications for a polymorphic function.
242         -- Hence the split*Rep*FunTys
243
244     ----------------------------
245         -- If fun_stricts is finite, it means the function returns bottom
246         -- after that number of value args have been consumed
247         -- Otherwise it's infinite, extended with False
248     fun_stricts
249       = case splitStrictSig (idNewStrictness fun) of
250           (demands, result_info)
251                 | not (demands `lengthExceeds` countValArgs orig_cont)
252                 ->      -- Enough args, use the strictness given.
253                         -- For bottoming functions we used to pretend that the arg
254                         -- is lazy, so that we don't treat the arg as an
255                         -- interesting context.  This avoids substituting
256                         -- top-level bindings for (say) strings into 
257                         -- calls to error.  But now we are more careful about
258                         -- inlining lone variables, so its ok (see SimplUtils.analyseCont)
259                    if isBotRes result_info then
260                         map isStrictDmd demands         -- Finite => result is bottom
261                    else
262                         map isStrictDmd demands ++ vanilla_stricts
263
264           other -> vanilla_stricts      -- Not enough args, or no strictness
265
266 -------------------
267 interestingArg :: OutExpr -> Bool
268         -- An argument is interesting if it has *some* structure
269         -- We are here trying to avoid unfolding a function that
270         -- is applied only to variables that have no unfolding
271         -- (i.e. they are probably lambda bound): f x y z
272         -- There is little point in inlining f here.
273 interestingArg (Var v)           = hasSomeUnfolding (idUnfolding v)
274                                         -- Was: isValueUnfolding (idUnfolding v')
275                                         -- But that seems over-pessimistic
276 interestingArg (Type _)          = False
277 interestingArg (App fn (Type _)) = interestingArg fn
278 interestingArg (Note _ a)        = interestingArg a
279 interestingArg other             = True
280         -- Consider     let x = 3 in f x
281         -- The substitution will contain (x -> ContEx 3), and we want to
282         -- to say that x is an interesting argument.
283         -- But consider also (\x. f x y) y
284         -- The substitution will contain (x -> ContEx y), and we want to say
285         -- that x is not interesting (assuming y has no unfolding)
286 \end{code}
287
288 Comment about interestingCallContext
289 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
290 We want to avoid inlining an expression where there can't possibly be
291 any gain, such as in an argument position.  Hence, if the continuation
292 is interesting (eg. a case scrutinee, application etc.) then we
293 inline, otherwise we don't.  
294
295 Previously some_benefit used to return True only if the variable was
296 applied to some value arguments.  This didn't work:
297
298         let x = _coerce_ (T Int) Int (I# 3) in
299         case _coerce_ Int (T Int) x of
300                 I# y -> ....
301
302 we want to inline x, but can't see that it's a constructor in a case
303 scrutinee position, and some_benefit is False.
304
305 Another example:
306
307 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
308
309 ....  case dMonadST _@_ x0 of (a,b,c) -> ....
310
311 we'd really like to inline dMonadST here, but we *don't* want to
312 inline if the case expression is just
313
314         case x of y { DEFAULT -> ... }
315
316 since we can just eliminate this case instead (x is in WHNF).  Similar
317 applies when x is bound to a lambda expression.  Hence
318 contIsInteresting looks for case expressions with just a single
319 default case.
320
321 \begin{code}
322 interestingCallContext :: Bool          -- False <=> no args at all
323                        -> Bool          -- False <=> no value args
324                        -> SimplCont -> Bool
325         -- The "lone-variable" case is important.  I spent ages
326         -- messing about with unsatisfactory varaints, but this is nice.
327         -- The idea is that if a variable appear all alone
328         --      as an arg of lazy fn, or rhs    Stop
329         --      as scrutinee of a case          Select
330         --      as arg of a strict fn           ArgOf
331         -- then we should not inline it (unless there is some other reason,
332         -- e.g. is is the sole occurrence).  We achieve this by making
333         -- interestingCallContext return False for a lone variable.
334         --
335         -- Why?  At least in the case-scrutinee situation, turning
336         --      let x = (a,b) in case x of y -> ...
337         -- into
338         --      let x = (a,b) in case (a,b) of y -> ...
339         -- and thence to 
340         --      let x = (a,b) in let y = (a,b) in ...
341         -- is bad if the binding for x will remain.
342         --
343         -- Another example: I discovered that strings
344         -- were getting inlined straight back into applications of 'error'
345         -- because the latter is strict.
346         --      s = "foo"
347         --      f = \x -> ...(error s)...
348
349         -- Fundamentally such contexts should not ecourage inlining because
350         -- the context can ``see'' the unfolding of the variable (e.g. case or a RULE)
351         -- so there's no gain.
352         --
353         -- However, even a type application or coercion isn't a lone variable.
354         -- Consider
355         --      case $fMonadST @ RealWorld of { :DMonad a b c -> c }
356         -- We had better inline that sucker!  The case won't see through it.
357         --
358         -- For now, I'm treating treating a variable applied to types 
359         -- in a *lazy* context "lone". The motivating example was
360         --      f = /\a. \x. BIG
361         --      g = /\a. \y.  h (f a)
362         -- There's no advantage in inlining f here, and perhaps
363         -- a significant disadvantage.  Hence some_val_args in the Stop case
364
365 interestingCallContext some_args some_val_args cont
366   = interesting cont
367   where
368     interesting (InlinePlease _)       = True
369     interesting (Select _ _ _ _ _)     = some_args
370     interesting (ApplyTo _ _ _ _)      = True   -- Can happen if we have (coerce t (f x)) y
371                                                 -- Perhaps True is a bit over-keen, but I've
372                                                 -- seen (coerce f) x, where f has an INLINE prag,
373                                                 -- So we have to give some motivaiton for inlining it
374     interesting (ArgOf _ _ _ _)          = some_val_args
375     interesting (Stop ty _ upd_in_place) = some_val_args && upd_in_place
376     interesting (CoerceIt _ cont)        = interesting cont
377         -- If this call is the arg of a strict function, the context
378         -- is a bit interesting.  If we inline here, we may get useful
379         -- evaluation information to avoid repeated evals: e.g.
380         --      x + (y * z)
381         -- Here the contIsInteresting makes the '*' keener to inline,
382         -- which in turn exposes a constructor which makes the '+' inline.
383         -- Assuming that +,* aren't small enough to inline regardless.
384         --
385         -- It's also very important to inline in a strict context for things
386         -- like
387         --              foldr k z (f x)
388         -- Here, the context of (f x) is strict, and if f's unfolding is
389         -- a build it's *great* to inline it here.  So we must ensure that
390         -- the context for (f x) is not totally uninteresting.
391
392
393 -------------------
394 canUpdateInPlace :: Type -> Bool
395 -- Consider   let x = <wurble> in ...
396 -- If <wurble> returns an explicit constructor, we might be able
397 -- to do update in place.  So we treat even a thunk RHS context
398 -- as interesting if update in place is possible.  We approximate
399 -- this by seeing if the type has a single constructor with a
400 -- small arity.  But arity zero isn't good -- we share the single copy
401 -- for that case, so no point in sharing.
402
403 canUpdateInPlace ty 
404   | not opt_UF_UpdateInPlace = False
405   | otherwise
406   = case splitTyConApp_maybe ty of 
407         Nothing         -> False 
408         Just (tycon, _) -> case tyConDataConsIfAvailable tycon of
409                                 [dc]  -> arity == 1 || arity == 2
410                                       where
411                                          arity = dataConRepArity dc
412                                 other -> False
413 \end{code}
414
415
416
417 %************************************************************************
418 %*                                                                      *
419 \section{Dealing with a single binder}
420 %*                                                                      *
421 %************************************************************************
422
423 These functions are in the monad only so that they can be made strict via seq.
424
425 \begin{code}
426 simplBinders :: SimplEnv -> [InBinder] -> SimplM (SimplEnv, [OutBinder])
427 simplBinders env bndrs
428   = let
429         (subst', bndrs') = Subst.simplBndrs (getSubst env) bndrs
430     in
431     seqBndrs bndrs'     `seq`
432     returnSmpl (setSubst env subst', bndrs')
433
434 simplBinder :: SimplEnv -> InBinder -> SimplM (SimplEnv, OutBinder)
435 simplBinder env bndr
436   = let
437         (subst', bndr') = Subst.simplBndr (getSubst env) bndr
438     in
439     seqBndr bndr'       `seq`
440     returnSmpl (setSubst env subst', bndr')
441
442
443 simplLetBndr :: SimplEnv -> InBinder -> SimplM (SimplEnv, OutBinder)
444 simplLetBndr env id
445   = let
446         (subst', id') = Subst.simplLetId (getSubst env) id
447     in
448     seqBndr id'         `seq`
449     returnSmpl (setSubst env subst', id')
450
451 simplLamBndrs, simplRecBndrs 
452         :: SimplEnv -> [InBinder] -> SimplM (SimplEnv, [OutBinder])
453 simplRecBndrs = simplBndrs Subst.simplLetId
454 simplLamBndrs = simplBndrs Subst.simplLamBndr
455
456 simplBndrs simpl_bndr env bndrs
457   = let
458         (subst', bndrs') = mapAccumL simpl_bndr (getSubst env) bndrs
459     in
460     seqBndrs bndrs'     `seq`
461     returnSmpl (setSubst env subst', bndrs')
462
463 seqBndrs [] = ()
464 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
465
466 seqBndr b | isTyVar b = b `seq` ()
467           | otherwise = seqType (idType b)      `seq`
468                         idInfo b                `seq`
469                         ()
470 \end{code}
471
472
473 \begin{code}
474 newId :: UserFS -> Type -> SimplM Id
475 newId fs ty = getUniqueSmpl     `thenSmpl` \ uniq ->
476               returnSmpl (mkSysLocal fs uniq ty)
477 \end{code}
478
479
480 %************************************************************************
481 %*                                                                      *
482 \subsection{Rebuilding a lambda}
483 %*                                                                      *
484 %************************************************************************
485
486 \begin{code}
487 mkLam :: SimplEnv -> [OutBinder] -> OutExpr -> SimplCont -> SimplM FloatsWithExpr
488 \end{code}
489
490 Try three things
491         a) eta reduction, if that gives a trivial expression
492         b) eta expansion [only if there are some value lambdas]
493         c) floating lets out through big lambdas 
494                 [only if all tyvar lambdas, and only if this lambda
495                  is the RHS of a let]
496
497 \begin{code}
498 mkLam env bndrs body cont
499  | opt_SimplDoEtaReduction,
500    Just etad_lam <- tryEtaReduce bndrs body
501  = tick (EtaReduction (head bndrs))     `thenSmpl_`
502    returnSmpl (emptyFloats env, etad_lam)
503
504  | opt_SimplDoLambdaEtaExpansion,
505    any isRuntimeVar bndrs
506  = tryEtaExpansion body         `thenSmpl` \ body' ->
507    returnSmpl (emptyFloats env, mkLams bndrs body')
508
509 {-      Sept 01: I'm experimenting with getting the
510         full laziness pass to float out past big lambdsa
511  | all isTyVar bndrs,   -- Only for big lambdas
512    contIsRhs cont       -- Only try the rhs type-lambda floating
513                         -- if this is indeed a right-hand side; otherwise
514                         -- we end up floating the thing out, only for float-in
515                         -- to float it right back in again!
516  = tryRhsTyLam env bndrs body           `thenSmpl` \ (floats, body') ->
517    returnSmpl (floats, mkLams bndrs body')
518 -}
519
520  | otherwise 
521  = returnSmpl (emptyFloats env, mkLams bndrs body)
522 \end{code}
523
524
525 %************************************************************************
526 %*                                                                      *
527 \subsection{Eta expansion and reduction}
528 %*                                                                      *
529 %************************************************************************
530
531 We try for eta reduction here, but *only* if we get all the 
532 way to an exprIsTrivial expression.    
533 We don't want to remove extra lambdas unless we are going 
534 to avoid allocating this thing altogether
535
536 \begin{code}
537 tryEtaReduce :: [OutBinder] -> OutExpr -> Maybe OutExpr
538 tryEtaReduce bndrs body 
539         -- We don't use CoreUtils.etaReduce, because we can be more
540         -- efficient here:
541         --  (a) we already have the binders
542         --  (b) we can do the triviality test before computing the free vars
543         --      [in fact I take the simple path and look for just a variable]
544   = go (reverse bndrs) body
545   where
546     go (b : bs) (App fun arg) | ok_arg b arg = go bs fun        -- Loop round
547     go []       (Var fun)     | ok_fun fun   = Just (Var fun)   -- Success!
548     go _        _                            = Nothing          -- Failure!
549
550     ok_fun fun = not (fun `elem` bndrs) && 
551                  (isEvaldUnfolding (idUnfolding fun) || all ok_lam bndrs)
552     ok_lam v = isTyVar v || isDictTy (idType v)
553         -- The isEvaldUnfolding is because eta reduction is not 
554         -- valid in general:  \x. bot  /=  bot
555         -- So we need to be sure that the "fun" is a value.
556         --
557         -- However, we always want to reduce (/\a -> f a) to f
558         -- This came up in a RULE: foldr (build (/\a -> g a))
559         --      did not match      foldr (build (/\b -> ...something complex...))
560         -- The type checker can insert these eta-expanded versions,
561         -- with both type and dictionary lambdas; hence the slightly 
562         -- ad-hoc isDictTy
563
564     ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
565 \end{code}
566
567
568         Try eta expansion for RHSs
569
570 We go for:
571    f = \x1..xn -> N  ==>   f = \x1..xn y1..ym -> N y1..ym
572                                  (n >= 0)
573
574 where (in both cases) 
575
576         * The xi can include type variables
577
578         * The yi are all value variables
579
580         * N is a NORMAL FORM (i.e. no redexes anywhere)
581           wanting a suitable number of extra args.
582
583 We may have to sandwich some coerces between the lambdas
584 to make the types work.   exprEtaExpandArity looks through coerces
585 when computing arity; and etaExpand adds the coerces as necessary when
586 actually computing the expansion.
587
588 \begin{code}
589 tryEtaExpansion :: OutExpr -> SimplM OutExpr
590 -- There is at least one runtime binder in the binders
591 tryEtaExpansion body
592   = getUniquesSmpl                      `thenSmpl` \ us ->
593     returnSmpl (etaExpand fun_arity us body (exprType body))
594   where
595     fun_arity = exprEtaExpandArity body
596 \end{code}
597
598
599 %************************************************************************
600 %*                                                                      *
601 \subsection{Floating lets out of big lambdas}
602 %*                                                                      *
603 %************************************************************************
604
605 tryRhsTyLam tries this transformation, when the big lambda appears as
606 the RHS of a let(rec) binding:
607
608         /\abc -> let(rec) x = e in b
609    ==>
610         let(rec) x' = /\abc -> let x = x' a b c in e
611         in 
612         /\abc -> let x = x' a b c in b
613
614 This is good because it can turn things like:
615
616         let f = /\a -> letrec g = ... g ... in g
617 into
618         letrec g' = /\a -> ... g' a ...
619         in
620         let f = /\ a -> g' a
621
622 which is better.  In effect, it means that big lambdas don't impede
623 let-floating.
624
625 This optimisation is CRUCIAL in eliminating the junk introduced by
626 desugaring mutually recursive definitions.  Don't eliminate it lightly!
627
628 So far as the implementation is concerned:
629
630         Invariant: go F e = /\tvs -> F e
631         
632         Equalities:
633                 go F (Let x=e in b)
634                 = Let x' = /\tvs -> F e 
635                   in 
636                   go G b
637                 where
638                     G = F . Let x = x' tvs
639         
640                 go F (Letrec xi=ei in b)
641                 = Letrec {xi' = /\tvs -> G ei} 
642                   in
643                   go G b
644                 where
645                   G = F . Let {xi = xi' tvs}
646
647 [May 1999]  If we do this transformation *regardless* then we can
648 end up with some pretty silly stuff.  For example, 
649
650         let 
651             st = /\ s -> let { x1=r1 ; x2=r2 } in ...
652         in ..
653 becomes
654         let y1 = /\s -> r1
655             y2 = /\s -> r2
656             st = /\s -> ...[y1 s/x1, y2 s/x2]
657         in ..
658
659 Unless the "..." is a WHNF there is really no point in doing this.
660 Indeed it can make things worse.  Suppose x1 is used strictly,
661 and is of the form
662
663         x1* = case f y of { (a,b) -> e }
664
665 If we abstract this wrt the tyvar we then can't do the case inline
666 as we would normally do.
667
668
669 \begin{code}
670 {-      Trying to do this in full laziness
671
672 tryRhsTyLam :: SimplEnv -> [OutTyVar] -> OutExpr -> SimplM FloatsWithExpr
673 -- Call ensures that all the binders are type variables
674
675 tryRhsTyLam env tyvars body             -- Only does something if there's a let
676   |  not (all isTyVar tyvars)
677   || not (worth_it body)                -- inside a type lambda, 
678   = returnSmpl (emptyFloats env, body)  -- and a WHNF inside that
679
680   | otherwise
681   = go env (\x -> x) body
682
683   where
684     worth_it e@(Let _ _) = whnf_in_middle e
685     worth_it e           = False
686
687     whnf_in_middle (Let (NonRec x rhs) e) | isUnLiftedType (idType x) = False
688     whnf_in_middle (Let _ e) = whnf_in_middle e
689     whnf_in_middle e         = exprIsCheap e
690
691     main_tyvar_set = mkVarSet tyvars
692
693     go env fn (Let bind@(NonRec var rhs) body)
694       | exprIsTrivial rhs
695       = go env (fn . Let bind) body
696
697     go env fn (Let (NonRec var rhs) body)
698       = mk_poly tyvars_here var                                                 `thenSmpl` \ (var', rhs') ->
699         addAuxiliaryBind env (NonRec var' (mkLams tyvars_here (fn rhs)))        $ \ env -> 
700         go env (fn . Let (mk_silly_bind var rhs')) body
701
702       where
703
704         tyvars_here = varSetElems (main_tyvar_set `intersectVarSet` exprSomeFreeVars isTyVar rhs)
705                 -- Abstract only over the type variables free in the rhs
706                 -- wrt which the new binding is abstracted.  But the naive
707                 -- approach of abstract wrt the tyvars free in the Id's type
708                 -- fails. Consider:
709                 --      /\ a b -> let t :: (a,b) = (e1, e2)
710                 --                    x :: a     = fst t
711                 --                in ...
712                 -- Here, b isn't free in x's type, but we must nevertheless
713                 -- abstract wrt b as well, because t's type mentions b.
714                 -- Since t is floated too, we'd end up with the bogus:
715                 --      poly_t = /\ a b -> (e1, e2)
716                 --      poly_x = /\ a   -> fst (poly_t a *b*)
717                 -- So for now we adopt the even more naive approach of
718                 -- abstracting wrt *all* the tyvars.  We'll see if that
719                 -- gives rise to problems.   SLPJ June 98
720
721     go env fn (Let (Rec prs) body)
722        = mapAndUnzipSmpl (mk_poly tyvars_here) vars     `thenSmpl` \ (vars', rhss') ->
723          let
724             gn body = fn (foldr Let body (zipWith mk_silly_bind vars rhss'))
725             pairs   = vars' `zip` [mkLams tyvars_here (gn rhs) | rhs <- rhss]
726          in
727          addAuxiliaryBind env (Rec pairs)               $ \ env ->
728          go env gn body 
729        where
730          (vars,rhss) = unzip prs
731          tyvars_here = varSetElems (main_tyvar_set `intersectVarSet` exprsSomeFreeVars isTyVar (map snd prs))
732                 -- See notes with tyvars_here above
733
734     go env fn body = returnSmpl (emptyFloats env, fn body)
735
736     mk_poly tyvars_here var
737       = getUniqueSmpl           `thenSmpl` \ uniq ->
738         let
739             poly_name = setNameUnique (idName var) uniq         -- Keep same name
740             poly_ty   = mkForAllTys tyvars_here (idType var)    -- But new type of course
741             poly_id   = mkLocalId poly_name poly_ty 
742
743                 -- In the olden days, it was crucial to copy the occInfo of the original var, 
744                 -- because we were looking at occurrence-analysed but as yet unsimplified code!
745                 -- In particular, we mustn't lose the loop breakers.  BUT NOW we are looking
746                 -- at already simplified code, so it doesn't matter
747                 -- 
748                 -- It's even right to retain single-occurrence or dead-var info:
749                 -- Suppose we started with  /\a -> let x = E in B
750                 -- where x occurs once in B. Then we transform to:
751                 --      let x' = /\a -> E in /\a -> let x* = x' a in B
752                 -- where x* has an INLINE prag on it.  Now, once x* is inlined,
753                 -- the occurrences of x' will be just the occurrences originally
754                 -- pinned on x.
755         in
756         returnSmpl (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tyvars_here))
757
758     mk_silly_bind var rhs = NonRec var (Note InlineMe rhs)
759                 -- Suppose we start with:
760                 --
761                 --      x = /\ a -> let g = G in E
762                 --
763                 -- Then we'll float to get
764                 --
765                 --      x = let poly_g = /\ a -> G
766                 --          in /\ a -> let g = poly_g a in E
767                 --
768                 -- But now the occurrence analyser will see just one occurrence
769                 -- of poly_g, not inside a lambda, so the simplifier will
770                 -- PreInlineUnconditionally poly_g back into g!  Badk to square 1!
771                 -- (I used to think that the "don't inline lone occurrences" stuff
772                 --  would stop this happening, but since it's the *only* occurrence,
773                 --  PreInlineUnconditionally kicks in first!)
774                 --
775                 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
776                 --           to appear many times.  (NB: mkInlineMe eliminates
777                 --           such notes on trivial RHSs, so do it manually.)
778 -}
779 \end{code}
780
781
782 %************************************************************************
783 %*                                                                      *
784 \subsection{Case absorption and identity-case elimination}
785 %*                                                                      *
786 %************************************************************************
787
788 mkCase puts a case expression back together, trying various transformations first.
789
790 \begin{code}
791 mkCase :: OutExpr -> [AltCon] -> OutId -> [OutAlt] -> SimplM OutExpr
792
793 mkCase scrut handled_cons case_bndr alts
794   = mkAlts scrut handled_cons case_bndr alts    `thenSmpl` \ better_alts ->
795     mkCase1 scrut case_bndr better_alts
796 \end{code}
797
798
799 mkAlts tries these things:
800
801 1.  If several alternatives are identical, merge them into
802     a single DEFAULT alternative.  I've occasionally seen this 
803     making a big difference:
804
805         case e of               =====>     case e of
806           C _ -> f x                         D v -> ....v....
807           D v -> ....v....                   DEFAULT -> f x
808           DEFAULT -> f x
809
810    The point is that we merge common RHSs, at least for the DEFAULT case.
811    [One could do something more elaborate but I've never seen it needed.]
812    To avoid an expensive test, we just merge branches equal to the *first*
813    alternative; this picks up the common cases
814         a) all branches equal
815         b) some branches equal to the DEFAULT (which occurs first)
816
817 2.  If the DEFAULT alternative can match only one possible constructor,
818     then make that constructor explicit.
819     e.g.
820         case e of x { DEFAULT -> rhs }
821      ===>
822         case e of x { (a,b) -> rhs }
823     where the type is a single constructor type.  This gives better code
824     when rhs also scrutinises x or e.
825
826 3.  Case merging:
827        case e of b {             ==>   case e of b {
828          p1 -> rhs1                      p1 -> rhs1
829          ...                             ...
830          pm -> rhsm                      pm -> rhsm
831          _  -> case b of b' {            pn -> let b'=b in rhsn
832                      pn -> rhsn          ...
833                      ...                 po -> let b'=b in rhso
834                      po -> rhso          _  -> let b'=b in rhsd
835                      _  -> rhsd
836        }  
837     
838     which merges two cases in one case when -- the default alternative of
839     the outer case scrutises the same variable as the outer case This
840     transformation is called Case Merging.  It avoids that the same
841     variable is scrutinised multiple times.
842
843
844 The case where transformation (1) showed up was like this (lib/std/PrelCError.lhs):
845
846         x | p `is` 1 -> e1
847           | p `is` 2 -> e2
848         ...etc...
849
850 where @is@ was something like
851         
852         p `is` n = p /= (-1) && p == n
853
854 This gave rise to a horrible sequence of cases
855
856         case p of
857           (-1) -> $j p
858           1    -> e1
859           DEFAULT -> $j p
860
861 and similarly in cascade for all the join points!
862
863
864
865 \begin{code}
866 --------------------------------------------------
867 --      1. Merge identical branches
868 --------------------------------------------------
869 mkAlts scrut handled_cons case_bndr alts@((con1,bndrs1,rhs1) : con_alts)
870   | all isDeadBinder bndrs1,                    -- Remember the default 
871     length filtered_alts < length con_alts      -- alternative comes first
872   = tick (AltMerge case_bndr)                   `thenSmpl_`
873     returnSmpl better_alts
874   where
875     filtered_alts        = filter keep con_alts
876     keep (con,bndrs,rhs) = not (all isDeadBinder bndrs && rhs `cheapEqExpr` rhs1)
877     better_alts          = (DEFAULT, [], rhs1) : filtered_alts
878
879
880 --------------------------------------------------
881 --      2. Fill in missing constructor
882 --------------------------------------------------
883
884 mkAlts scrut handled_cons case_bndr alts
885   | (alts_no_deflt, Just rhs) <- findDefault alts,
886                         -- There is a DEFAULT case
887
888     Just (tycon, inst_tys) <- splitTyConApp_maybe (idType case_bndr),
889     isAlgTyCon tycon,           -- It's a data type, tuple, or unboxed tuples.  
890     not (isNewTyCon tycon),     -- We can have a newtype, if we are just doing an eval:
891                                 --      case x of { DEFAULT -> e }
892                                 -- and we don't want to fill in a default for them!
893
894     [missing_con] <- [con | con <- tyConDataConsIfAvailable tycon,
895                             not (con `elem` handled_data_cons)]
896                         -- There is just one missing constructor!
897
898   = tick (FillInCaseDefault case_bndr)  `thenSmpl_`
899     getUniquesSmpl                      `thenSmpl` \ tv_uniqs ->
900     getUniquesSmpl                      `thenSmpl` \ id_uniqs ->
901     let
902         (_,_,ex_tyvars,_,_,_) = dataConSig missing_con
903         ex_tyvars'  = zipWith mk tv_uniqs ex_tyvars
904         mk uniq tv  = mkSysTyVar uniq (tyVarKind tv)
905         arg_ids     = zipWith (mkSysLocal SLIT("a")) id_uniqs arg_tys
906         arg_tys     = dataConArgTys missing_con (inst_tys ++ mkTyVarTys ex_tyvars')
907         better_alts = (DataAlt missing_con, ex_tyvars' ++ arg_ids, rhs) : alts_no_deflt
908     in
909     returnSmpl better_alts
910   where
911     handled_data_cons = [data_con | DataAlt data_con <- handled_cons]
912
913 --------------------------------------------------
914 --      3.  Merge nested cases
915 --------------------------------------------------
916
917 mkAlts scrut handled_cons outer_bndr outer_alts
918   | opt_SimplCaseMerge,
919     (outer_alts_without_deflt, maybe_outer_deflt)   <- findDefault outer_alts,
920     Just (Case (Var scrut_var) inner_bndr inner_alts) <- maybe_outer_deflt,
921     scruting_same_var scrut_var
922
923   = let     --  Eliminate any inner alts which are shadowed by the outer ones
924         outer_cons = [con | (con,_,_) <- outer_alts_without_deflt]
925     
926         munged_inner_alts = [ (con, args, munge_rhs rhs) 
927                             | (con, args, rhs) <- inner_alts, 
928                                not (con `elem` outer_cons)      -- Eliminate shadowed inner alts
929                             ]
930         munge_rhs rhs = bindCaseBndr inner_bndr (Var outer_bndr) rhs
931     
932         (inner_con_alts, maybe_inner_default) = findDefault munged_inner_alts
933
934         new_alts = add_default maybe_inner_default
935                                (outer_alts_without_deflt ++ inner_con_alts)
936     in
937     tick (CaseMerge outer_bndr)                         `thenSmpl_`
938     returnSmpl new_alts
939         -- Warning: don't call mkAlts recursively!
940         -- Firstly, there's no point, because inner alts have already had
941         -- mkCase applied to them, so they won't have a case in their default
942         -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr
943         -- in munge_rhs may put a case into the DEFAULT branch!
944   where
945         -- We are scrutinising the same variable if it's
946         -- the outer case-binder, or if the outer case scrutinises a variable
947         -- (and it's the same).  Testing both allows us not to replace the
948         -- outer scrut-var with the outer case-binder (Simplify.simplCaseBinder).
949     scruting_same_var = case scrut of
950                           Var outer_scrut -> \ v -> v == outer_bndr || v == outer_scrut
951                           other           -> \ v -> v == outer_bndr
952
953     add_default (Just rhs) alts = (DEFAULT,[],rhs) : alts
954     add_default Nothing    alts = alts
955
956
957 --------------------------------------------------
958 --      Catch-all
959 --------------------------------------------------
960
961 mkAlts scrut handled_cons case_bndr other_alts = returnSmpl other_alts
962 \end{code}
963
964
965
966 =================================================================================
967
968 mkCase1 tries these things
969
970 1.  Eliminate the case altogether if possible
971
972 2.  Case-identity:
973
974         case e of               ===> e
975                 True  -> True;
976                 False -> False
977
978     and similar friends.
979
980
981 Start with a simple situation:
982
983         case x# of      ===>   e[x#/y#]
984           y# -> e
985
986 (when x#, y# are of primitive type, of course).  We can't (in general)
987 do this for algebraic cases, because we might turn bottom into
988 non-bottom!
989
990 Actually, we generalise this idea to look for a case where we're
991 scrutinising a variable, and we know that only the default case can
992 match.  For example:
993 \begin{verbatim}
994         case x of
995           0#    -> ...
996           other -> ...(case x of
997                          0#    -> ...
998                          other -> ...) ...
999 \end{code}
1000 Here the inner case can be eliminated.  This really only shows up in
1001 eliminating error-checking code.
1002
1003 We also make sure that we deal with this very common case:
1004
1005         case e of 
1006           x -> ...x...
1007
1008 Here we are using the case as a strict let; if x is used only once
1009 then we want to inline it.  We have to be careful that this doesn't 
1010 make the program terminate when it would have diverged before, so we
1011 check that 
1012         - x is used strictly, or
1013         - e is already evaluated (it may so if e is a variable)
1014
1015 Lastly, we generalise the transformation to handle this:
1016
1017         case e of       ===> r
1018            True  -> r
1019            False -> r
1020
1021 We only do this for very cheaply compared r's (constructors, literals
1022 and variables).  If pedantic bottoms is on, we only do it when the
1023 scrutinee is a PrimOp which can't fail.
1024
1025 We do it *here*, looking at un-simplified alternatives, because we
1026 have to check that r doesn't mention the variables bound by the
1027 pattern in each alternative, so the binder-info is rather useful.
1028
1029 So the case-elimination algorithm is:
1030
1031         1. Eliminate alternatives which can't match
1032
1033         2. Check whether all the remaining alternatives
1034                 (a) do not mention in their rhs any of the variables bound in their pattern
1035            and  (b) have equal rhss
1036
1037         3. Check we can safely ditch the case:
1038                    * PedanticBottoms is off,
1039                 or * the scrutinee is an already-evaluated variable
1040                 or * the scrutinee is a primop which is ok for speculation
1041                         -- ie we want to preserve divide-by-zero errors, and
1042                         -- calls to error itself!
1043
1044                 or * [Prim cases] the scrutinee is a primitive variable
1045
1046                 or * [Alg cases] the scrutinee is a variable and
1047                      either * the rhs is the same variable
1048                         (eg case x of C a b -> x  ===>   x)
1049                      or     * there is only one alternative, the default alternative,
1050                                 and the binder is used strictly in its scope.
1051                                 [NB this is helped by the "use default binder where
1052                                  possible" transformation; see below.]
1053
1054
1055 If so, then we can replace the case with one of the rhss.
1056
1057 Further notes about case elimination
1058 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1059 Consider:       test :: Integer -> IO ()
1060                 test = print
1061
1062 Turns out that this compiles to:
1063     Print.test
1064       = \ eta :: Integer
1065           eta1 :: State# RealWorld ->
1066           case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT ->
1067           case hPutStr stdout
1068                  (PrelNum.jtos eta ($w[] @ Char))
1069                  eta1
1070           of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s  }}
1071
1072 Notice the strange '<' which has no effect at all. This is a funny one.  
1073 It started like this:
1074
1075 f x y = if x < 0 then jtos x
1076           else if y==0 then "" else jtos x
1077
1078 At a particular call site we have (f v 1).  So we inline to get
1079
1080         if v < 0 then jtos x 
1081         else if 1==0 then "" else jtos x
1082
1083 Now simplify the 1==0 conditional:
1084
1085         if v<0 then jtos v else jtos v
1086
1087 Now common-up the two branches of the case:
1088
1089         case (v<0) of DEFAULT -> jtos v
1090
1091 Why don't we drop the case?  Because it's strict in v.  It's technically
1092 wrong to drop even unnecessary evaluations, and in practice they
1093 may be a result of 'seq' so we *definitely* don't want to drop those.
1094 I don't really know how to improve this situation.
1095
1096
1097 \begin{code}
1098 --------------------------------------------------
1099 --      1. Eliminate the case altogether if poss
1100 --------------------------------------------------
1101
1102 mkCase1 scrut case_bndr [(con,bndrs,rhs)]
1103   -- See if we can get rid of the case altogether
1104   -- See the extensive notes on case-elimination above
1105   -- mkCase made sure that if all the alternatives are equal, 
1106   -- then there is now only one (DEFAULT) rhs
1107  |  all isDeadBinder bndrs,
1108
1109         -- Check that the scrutinee can be let-bound instead of case-bound
1110     exprOkForSpeculation scrut
1111                 -- OK not to evaluate it
1112                 -- This includes things like (==# a# b#)::Bool
1113                 -- so that we simplify 
1114                 --      case ==# a# b# of { True -> x; False -> x }
1115                 -- to just
1116                 --      x
1117                 -- This particular example shows up in default methods for
1118                 -- comparision operations (e.g. in (>=) for Int.Int32)
1119         || exprIsValue scrut                    -- It's already evaluated
1120         || var_demanded_later scrut             -- It'll be demanded later
1121
1122 --      || not opt_SimplPedanticBottoms)        -- Or we don't care!
1123 --      We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1124 --      but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1125 --      its argument:  case x of { y -> dataToTag# y }
1126 --      Here we must *not* discard the case, because dataToTag# just fetches the tag from
1127 --      the info pointer.  So we'll be pedantic all the time, and see if that gives any
1128 --      other problems
1129 --      Also we don't want to discard 'seq's
1130   = tick (CaseElim case_bndr)                   `thenSmpl_` 
1131     returnSmpl (bindCaseBndr case_bndr scrut rhs)
1132
1133   where
1134         -- The case binder is going to be evaluated later, 
1135         -- and the scrutinee is a simple variable
1136     var_demanded_later (Var v) = isStrictDmd (idNewDemandInfo case_bndr)
1137     var_demanded_later other   = False
1138
1139
1140 --------------------------------------------------
1141 --      2. Identity case
1142 --------------------------------------------------
1143
1144 mkCase1 scrut case_bndr alts    -- Identity case
1145   | all identity_alt alts
1146   = tick (CaseIdentity case_bndr)               `thenSmpl_`
1147     returnSmpl (re_note scrut)
1148   where
1149     identity_alt (con, args, rhs) = de_note rhs `cheapEqExpr` identity_rhs con args
1150
1151     identity_rhs (DataAlt con) args = mkConApp con (arg_tys ++ map varToCoreExpr args)
1152     identity_rhs (LitAlt lit)  _    = Lit lit
1153     identity_rhs DEFAULT       _    = Var case_bndr
1154
1155     arg_tys = map Type (tyConAppArgs (idType case_bndr))
1156
1157         -- We've seen this:
1158         --      case coerce T e of x { _ -> coerce T' x }
1159         -- And we definitely want to eliminate this case!
1160         -- So we throw away notes from the RHS, and reconstruct
1161         -- (at least an approximation) at the other end
1162     de_note (Note _ e) = de_note e
1163     de_note e          = e
1164
1165         -- re_note wraps a coerce if it might be necessary
1166     re_note scrut = case head alts of
1167                         (_,_,rhs1@(Note _ _)) -> mkCoerce (exprType rhs1) (idType case_bndr) scrut
1168                         other                 -> scrut
1169
1170
1171 --------------------------------------------------
1172 --      Catch-all
1173 --------------------------------------------------
1174 mkCase1 scrut bndr alts = returnSmpl (Case scrut bndr alts)
1175 \end{code}
1176
1177
1178 When adding auxiliary bindings for the case binder, it's worth checking if
1179 its dead, because it often is, and occasionally these mkCase transformations
1180 cascade rather nicely.
1181
1182 \begin{code}
1183 bindCaseBndr bndr rhs body
1184   | isDeadBinder bndr = body
1185   | otherwise         = bindNonRec bndr rhs body
1186 \end{code}