2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section[SimplUtils]{The simplifier utilities}
8 simplBinder, simplBinders, simplRecIds, simplLetId,
9 tryRhsTyLam, tryEtaExpansion,
12 -- The continuation type
13 SimplCont(..), DupFlag(..), contIsDupable, contResultType,
14 countValArgs, countArgs, mkRhsStop, mkStop,
15 getContArgs, interestingCallContext, interestingArg, isStrictType, discardInline
19 #include "HsVersions.h"
21 import CmdLineOpts ( switchIsOn, SimplifierSwitch(..),
22 opt_SimplDoLambdaEtaExpansion, opt_SimplCaseMerge,
26 import CoreUtils ( exprIsTrivial, cheapEqExpr, exprType, exprIsCheap,
27 etaExpand, exprEtaExpandArity, bindNonRec, mkCoerce,
30 import Subst ( InScopeSet, mkSubst, substExpr )
31 import qualified Subst ( simplBndrs, simplBndr, simplLetId )
32 import Id ( idType, idName,
33 idUnfolding, idNewStrictness,
36 import IdInfo ( StrictnessInfo(..) )
37 import Maybes ( maybeToBool, catMaybes )
38 import Name ( setNameUnique )
39 import NewDemand ( isStrictDmd, isBotRes, splitStrictSig )
41 import Type ( Type, mkForAllTys, seqType,
42 splitTyConApp_maybe, tyConAppArgs, mkTyVarTys,
46 import TcType ( isStrictType )
47 import TyCon ( tyConDataConsIfAvailable )
48 import DataCon ( dataConRepArity )
49 import VarEnv ( SubstEnv )
50 import Util ( lengthExceeds, mapAccumL )
55 %************************************************************************
57 \subsection{The continuation data type}
59 %************************************************************************
62 data SimplCont -- Strict contexts
63 = Stop OutType -- Type of the result
64 Bool -- True => This is the RHS of a thunk whose type suggests
65 -- that update-in-place would be possible
66 -- (This makes the inliner a little keener.)
68 | CoerceIt OutType -- The To-type, simplified
71 | InlinePlease -- This continuation makes a function very
72 SimplCont -- keen to inline itelf
75 InExpr SubstEnv -- The argument, as yet unsimplified,
76 SimplCont -- and its subst-env
79 InId [InAlt] SubstEnv -- The case binder, alts, and subst-env
82 | ArgOf DupFlag -- An arbitrary strict context: the argument
83 -- of a strict function, or a primitive-arg fn
85 OutType -- cont_ty: the type of the expression being sought by the context
86 -- f (error "foo") ==> coerce t (error "foo")
88 -- We need to know the type t, to which to coerce.
89 (OutExpr -> SimplM OutExprStuff) -- What to do with the result
90 -- The result expression in the OutExprStuff has type cont_ty
92 instance Outputable SimplCont where
93 ppr (Stop _ _) = ptext SLIT("Stop")
94 ppr (ApplyTo dup arg se cont) = (ptext SLIT("ApplyTo") <+> ppr dup <+> ppr arg) $$ ppr cont
95 ppr (ArgOf dup _ _) = ptext SLIT("ArgOf...") <+> ppr dup
96 ppr (Select dup bndr alts se cont) = (ptext SLIT("Select") <+> ppr dup <+> ppr bndr) $$
97 (nest 4 (ppr alts)) $$ ppr cont
98 ppr (CoerceIt ty cont) = (ptext SLIT("CoerceIt") <+> ppr ty) $$ ppr cont
99 ppr (InlinePlease cont) = ptext SLIT("InlinePlease") $$ ppr cont
101 data DupFlag = OkToDup | NoDup
103 instance Outputable DupFlag where
104 ppr OkToDup = ptext SLIT("ok")
105 ppr NoDup = ptext SLIT("nodup")
109 mkRhsStop, mkStop :: OutType -> SimplCont
110 mkStop ty = Stop ty False
111 mkRhsStop ty = Stop ty (canUpdateInPlace ty)
115 contIsDupable :: SimplCont -> Bool
116 contIsDupable (Stop _ _) = True
117 contIsDupable (ApplyTo OkToDup _ _ _) = True
118 contIsDupable (ArgOf OkToDup _ _) = True
119 contIsDupable (Select OkToDup _ _ _ _) = True
120 contIsDupable (CoerceIt _ cont) = contIsDupable cont
121 contIsDupable (InlinePlease cont) = contIsDupable cont
122 contIsDupable other = False
125 discardInline :: SimplCont -> SimplCont
126 discardInline (InlinePlease cont) = cont
127 discardInline (ApplyTo d e s cont) = ApplyTo d e s (discardInline cont)
128 discardInline cont = cont
131 discardableCont :: SimplCont -> Bool
132 discardableCont (Stop _ _) = False
133 discardableCont (CoerceIt _ cont) = discardableCont cont
134 discardableCont (InlinePlease cont) = discardableCont cont
135 discardableCont other = True
137 discardCont :: SimplCont -- A continuation, expecting
138 -> SimplCont -- Replace the continuation with a suitable coerce
139 discardCont cont = case cont of
141 other -> CoerceIt to_ty (mkStop to_ty)
143 to_ty = contResultType cont
146 contResultType :: SimplCont -> OutType
147 contResultType (Stop to_ty _) = to_ty
148 contResultType (ArgOf _ to_ty _) = to_ty
149 contResultType (ApplyTo _ _ _ cont) = contResultType cont
150 contResultType (CoerceIt _ cont) = contResultType cont
151 contResultType (InlinePlease cont) = contResultType cont
152 contResultType (Select _ _ _ _ cont) = contResultType cont
155 countValArgs :: SimplCont -> Int
156 countValArgs (ApplyTo _ (Type ty) se cont) = countValArgs cont
157 countValArgs (ApplyTo _ val_arg se cont) = 1 + countValArgs cont
158 countValArgs other = 0
160 countArgs :: SimplCont -> Int
161 countArgs (ApplyTo _ arg se cont) = 1 + countArgs cont
167 getContArgs :: OutId -> SimplCont
168 -> SimplM ([(InExpr, SubstEnv, Bool)], -- Arguments; the Bool is true for strict args
169 SimplCont, -- Remaining continuation
170 Bool) -- Whether we came across an InlineCall
171 -- getContArgs id k = (args, k', inl)
172 -- args are the leading ApplyTo items in k
173 -- (i.e. outermost comes first)
174 -- augmented with demand info from the functionn
175 getContArgs fun orig_cont
176 = getSwitchChecker `thenSmpl` \ chkr ->
178 -- Ignore strictness info if the no-case-of-case
179 -- flag is on. Strictness changes evaluation order
180 -- and that can change full laziness
181 stricts | switchIsOn chkr NoCaseOfCase = vanilla_stricts
182 | otherwise = computed_stricts
184 go [] stricts False orig_cont
186 ----------------------------
189 go acc ss inl (ApplyTo _ arg@(Type _) se cont)
190 = go ((arg,se,False) : acc) ss inl cont
191 -- NB: don't bother to instantiate the function type
194 go acc (s:ss) inl (ApplyTo _ arg se cont)
195 = go ((arg,se,s) : acc) ss inl cont
197 -- An Inline continuation
198 go acc ss inl (InlinePlease cont)
199 = go acc ss True cont
201 -- We're run out of arguments, or else we've run out of demands
202 -- The latter only happens if the result is guaranteed bottom
203 -- This is the case for
204 -- * case (error "hello") of { ... }
205 -- * (error "Hello") arg
206 -- * f (error "Hello") where f is strict
209 | null ss && discardableCont cont = tick BottomFound `thenSmpl_`
210 returnSmpl (reverse acc, discardCont cont, inl)
211 | otherwise = returnSmpl (reverse acc, cont, inl)
213 ----------------------------
214 vanilla_stricts, computed_stricts :: [Bool]
215 vanilla_stricts = repeat False
216 computed_stricts = zipWith (||) fun_stricts arg_stricts
218 ----------------------------
219 (val_arg_tys, _) = splitRepFunTys (idType fun)
220 arg_stricts = map isStrictType val_arg_tys ++ repeat False
221 -- These argument types are used as a cheap and cheerful way to find
222 -- unboxed arguments, which must be strict. But it's an InType
223 -- and so there might be a type variable where we expect a function
224 -- type (the substitution hasn't happened yet). And we don't bother
225 -- doing the type applications for a polymorphic function.
226 -- Hence the split*Rep*FunTys
228 ----------------------------
229 -- If fun_stricts is finite, it means the function returns bottom
230 -- after that number of value args have been consumed
231 -- Otherwise it's infinite, extended with False
233 = case splitStrictSig (idNewStrictness fun) of
234 (demands, result_info)
235 | not (demands `lengthExceeds` countValArgs orig_cont)
236 -> -- Enough args, use the strictness given.
237 -- For bottoming functions we used to pretend that the arg
238 -- is lazy, so that we don't treat the arg as an
239 -- interesting context. This avoids substituting
240 -- top-level bindings for (say) strings into
241 -- calls to error. But now we are more careful about
242 -- inlining lone variables, so its ok (see SimplUtils.analyseCont)
243 if isBotRes result_info then
244 map isStrictDmd demands -- Finite => result is bottom
246 map isStrictDmd demands ++ vanilla_stricts
248 other -> vanilla_stricts -- Not enough args, or no strictness
251 interestingArg :: InScopeSet -> InExpr -> SubstEnv -> Bool
252 -- An argument is interesting if it has *some* structure
253 -- We are here trying to avoid unfolding a function that
254 -- is applied only to variables that have no unfolding
255 -- (i.e. they are probably lambda bound): f x y z
256 -- There is little point in inlining f here.
257 interestingArg in_scope arg subst
258 = analyse (substExpr (mkSubst in_scope subst) arg)
259 -- 'analyse' only looks at the top part of the result
260 -- and substExpr is lazy, so this isn't nearly as brutal
263 analyse (Var v) = hasSomeUnfolding (idUnfolding v)
264 -- Was: isValueUnfolding (idUnfolding v')
265 -- But that seems over-pessimistic
266 analyse (Type _) = False
267 analyse (App fn (Type _)) = analyse fn
268 analyse (Note _ a) = analyse a
270 -- Consider let x = 3 in f x
271 -- The substitution will contain (x -> ContEx 3), and we want to
272 -- to say that x is an interesting argument.
273 -- But consider also (\x. f x y) y
274 -- The substitution will contain (x -> ContEx y), and we want to say
275 -- that x is not interesting (assuming y has no unfolding)
278 Comment about interestingCallContext
279 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
280 We want to avoid inlining an expression where there can't possibly be
281 any gain, such as in an argument position. Hence, if the continuation
282 is interesting (eg. a case scrutinee, application etc.) then we
283 inline, otherwise we don't.
285 Previously some_benefit used to return True only if the variable was
286 applied to some value arguments. This didn't work:
288 let x = _coerce_ (T Int) Int (I# 3) in
289 case _coerce_ Int (T Int) x of
292 we want to inline x, but can't see that it's a constructor in a case
293 scrutinee position, and some_benefit is False.
297 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
299 .... case dMonadST _@_ x0 of (a,b,c) -> ....
301 we'd really like to inline dMonadST here, but we *don't* want to
302 inline if the case expression is just
304 case x of y { DEFAULT -> ... }
306 since we can just eliminate this case instead (x is in WHNF). Similar
307 applies when x is bound to a lambda expression. Hence
308 contIsInteresting looks for case expressions with just a single
312 interestingCallContext :: Bool -- False <=> no args at all
313 -> Bool -- False <=> no value args
315 -- The "lone-variable" case is important. I spent ages
316 -- messing about with unsatisfactory varaints, but this is nice.
317 -- The idea is that if a variable appear all alone
318 -- as an arg of lazy fn, or rhs Stop
319 -- as scrutinee of a case Select
320 -- as arg of a strict fn ArgOf
321 -- then we should not inline it (unless there is some other reason,
322 -- e.g. is is the sole occurrence). We achieve this by making
323 -- interestingCallContext return False for a lone variable.
325 -- Why? At least in the case-scrutinee situation, turning
326 -- let x = (a,b) in case x of y -> ...
328 -- let x = (a,b) in case (a,b) of y -> ...
330 -- let x = (a,b) in let y = (a,b) in ...
331 -- is bad if the binding for x will remain.
333 -- Another example: I discovered that strings
334 -- were getting inlined straight back into applications of 'error'
335 -- because the latter is strict.
337 -- f = \x -> ...(error s)...
339 -- Fundamentally such contexts should not ecourage inlining becuase
340 -- the context can ``see'' the unfolding of the variable (e.g. case or a RULE)
341 -- so there's no gain.
343 -- However, even a type application or coercion isn't a lone variable.
345 -- case $fMonadST @ RealWorld of { :DMonad a b c -> c }
346 -- We had better inline that sucker! The case won't see through it.
348 -- For now, I'm treating treating a variable applied to types
349 -- in a *lazy* context "lone". The motivating example was
351 -- g = /\a. \y. h (f a)
352 -- There's no advantage in inlining f here, and perhaps
353 -- a significant disadvantage. Hence some_val_args in the Stop case
355 interestingCallContext some_args some_val_args cont
358 interesting (InlinePlease _) = True
359 interesting (Select _ _ _ _ _) = some_args
360 interesting (ApplyTo _ _ _ _) = True -- Can happen if we have (coerce t (f x)) y
361 -- Perhaps True is a bit over-keen, but I've
362 -- seen (coerce f) x, where f has an INLINE prag,
363 -- So we have to give some motivaiton for inlining it
364 interesting (ArgOf _ _ _) = some_val_args
365 interesting (Stop ty upd_in_place) = some_val_args && upd_in_place
366 interesting (CoerceIt _ cont) = interesting cont
367 -- If this call is the arg of a strict function, the context
368 -- is a bit interesting. If we inline here, we may get useful
369 -- evaluation information to avoid repeated evals: e.g.
371 -- Here the contIsInteresting makes the '*' keener to inline,
372 -- which in turn exposes a constructor which makes the '+' inline.
373 -- Assuming that +,* aren't small enough to inline regardless.
375 -- It's also very important to inline in a strict context for things
378 -- Here, the context of (f x) is strict, and if f's unfolding is
379 -- a build it's *great* to inline it here. So we must ensure that
380 -- the context for (f x) is not totally uninteresting.
384 canUpdateInPlace :: Type -> Bool
385 -- Consider let x = <wurble> in ...
386 -- If <wurble> returns an explicit constructor, we might be able
387 -- to do update in place. So we treat even a thunk RHS context
388 -- as interesting if update in place is possible. We approximate
389 -- this by seeing if the type has a single constructor with a
390 -- small arity. But arity zero isn't good -- we share the single copy
391 -- for that case, so no point in sharing.
394 | not opt_UF_UpdateInPlace = False
396 = case splitTyConApp_maybe ty of
398 Just (tycon, _) -> case tyConDataConsIfAvailable tycon of
399 [dc] -> arity == 1 || arity == 2
401 arity = dataConRepArity dc
407 %************************************************************************
409 \section{Dealing with a single binder}
411 %************************************************************************
414 simplBinders :: [InBinder] -> ([OutBinder] -> SimplM a) -> SimplM a
415 simplBinders bndrs thing_inside
416 = getSubst `thenSmpl` \ subst ->
418 (subst', bndrs') = Subst.simplBndrs subst bndrs
420 seqBndrs bndrs' `seq`
421 setSubst subst' (thing_inside bndrs')
423 simplBinder :: InBinder -> (OutBinder -> SimplM a) -> SimplM a
424 simplBinder bndr thing_inside
425 = getSubst `thenSmpl` \ subst ->
427 (subst', bndr') = Subst.simplBndr subst bndr
430 setSubst subst' (thing_inside bndr')
433 simplRecIds :: [InBinder] -> ([OutBinder] -> SimplM a) -> SimplM a
434 simplRecIds ids thing_inside
435 = getSubst `thenSmpl` \ subst ->
437 (subst', ids') = mapAccumL Subst.simplLetId subst ids
440 setSubst subst' (thing_inside ids')
442 simplLetId :: InBinder -> (OutBinder -> SimplM a) -> SimplM a
443 simplLetId id thing_inside
444 = getSubst `thenSmpl` \ subst ->
446 (subst', id') = Subst.simplLetId subst id
449 setSubst subst' (thing_inside id')
452 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
454 seqBndr b | isTyVar b = b `seq` ()
455 | otherwise = seqType (idType b) `seq`
461 %************************************************************************
463 \subsection{Local tyvar-lifting}
465 %************************************************************************
467 mkRhsTyLam tries this transformation, when the big lambda appears as
468 the RHS of a let(rec) binding:
470 /\abc -> let(rec) x = e in b
472 let(rec) x' = /\abc -> let x = x' a b c in e
474 /\abc -> let x = x' a b c in b
476 This is good because it can turn things like:
478 let f = /\a -> letrec g = ... g ... in g
480 letrec g' = /\a -> ... g' a ...
484 which is better. In effect, it means that big lambdas don't impede
487 This optimisation is CRUCIAL in eliminating the junk introduced by
488 desugaring mutually recursive definitions. Don't eliminate it lightly!
490 So far as the implementation is concerned:
492 Invariant: go F e = /\tvs -> F e
496 = Let x' = /\tvs -> F e
500 G = F . Let x = x' tvs
502 go F (Letrec xi=ei in b)
503 = Letrec {xi' = /\tvs -> G ei}
507 G = F . Let {xi = xi' tvs}
509 [May 1999] If we do this transformation *regardless* then we can
510 end up with some pretty silly stuff. For example,
513 st = /\ s -> let { x1=r1 ; x2=r2 } in ...
518 st = /\s -> ...[y1 s/x1, y2 s/x2]
521 Unless the "..." is a WHNF there is really no point in doing this.
522 Indeed it can make things worse. Suppose x1 is used strictly,
525 x1* = case f y of { (a,b) -> e }
527 If we abstract this wrt the tyvar we then can't do the case inline
528 as we would normally do.
532 tryRhsTyLam :: OutExpr -> SimplM ([OutBind], OutExpr)
534 tryRhsTyLam rhs -- Only does something if there's a let
535 | null tyvars || not (worth_it body) -- inside a type lambda,
536 = returnSmpl ([], rhs) -- and a WHNF inside that
539 = go (\x -> x) body `thenSmpl` \ (binds, body') ->
540 returnSmpl (binds, mkLams tyvars body')
543 (tyvars, body) = collectTyBinders rhs
545 worth_it e@(Let _ _) = whnf_in_middle e
548 whnf_in_middle (Let (NonRec x rhs) e) | isUnLiftedType (idType x) = False
549 whnf_in_middle (Let _ e) = whnf_in_middle e
550 whnf_in_middle e = exprIsCheap e
552 go fn (Let bind@(NonRec var rhs) body)
554 = go (fn . Let bind) body
556 go fn (Let (NonRec var rhs) body)
557 = mk_poly tyvars_here var `thenSmpl` \ (var', rhs') ->
558 go (fn . Let (mk_silly_bind var rhs')) body `thenSmpl` \ (binds, body') ->
559 returnSmpl (NonRec var' (mkLams tyvars_here (fn rhs)) : binds, body')
563 -- main_tyvar_set = mkVarSet tyvars
564 -- var_ty = idType var
565 -- varSetElems (main_tyvar_set `intersectVarSet` tyVarsOfType var_ty)
566 -- tyvars_here was an attempt to reduce the number of tyvars
567 -- wrt which the new binding is abstracted. But the naive
568 -- approach of abstract wrt the tyvars free in the Id's type
570 -- /\ a b -> let t :: (a,b) = (e1, e2)
573 -- Here, b isn't free in x's type, but we must nevertheless
574 -- abstract wrt b as well, because t's type mentions b.
575 -- Since t is floated too, we'd end up with the bogus:
576 -- poly_t = /\ a b -> (e1, e2)
577 -- poly_x = /\ a -> fst (poly_t a *b*)
578 -- So for now we adopt the even more naive approach of
579 -- abstracting wrt *all* the tyvars. We'll see if that
580 -- gives rise to problems. SLPJ June 98
582 go fn (Let (Rec prs) body)
583 = mapAndUnzipSmpl (mk_poly tyvars_here) vars `thenSmpl` \ (vars', rhss') ->
585 gn body = fn (foldr Let body (zipWith mk_silly_bind vars rhss'))
586 new_bind = Rec (vars' `zip` [mkLams tyvars_here (gn rhs) | rhs <- rhss])
588 go gn body `thenSmpl` \ (binds, body') ->
589 returnSmpl (new_bind : binds, body')
591 (vars,rhss) = unzip prs
593 -- varSetElems (main_tyvar_set `intersectVarSet` tyVarsOfTypes var_tys)
594 -- var_tys = map idType vars
595 -- See notes with tyvars_here above
597 go fn body = returnSmpl ([], fn body)
599 mk_poly tyvars_here var
600 = getUniqueSmpl `thenSmpl` \ uniq ->
602 poly_name = setNameUnique (idName var) uniq -- Keep same name
603 poly_ty = mkForAllTys tyvars_here (idType var) -- But new type of course
604 poly_id = mkLocalId poly_name poly_ty
606 -- In the olden days, it was crucial to copy the occInfo of the original var,
607 -- because we were looking at occurrence-analysed but as yet unsimplified code!
608 -- In particular, we mustn't lose the loop breakers. BUT NOW we are looking
609 -- at already simplified code, so it doesn't matter
611 -- It's even right to retain single-occurrence or dead-var info:
612 -- Suppose we started with /\a -> let x = E in B
613 -- where x occurs once in B. Then we transform to:
614 -- let x' = /\a -> E in /\a -> let x* = x' a in B
615 -- where x* has an INLINE prag on it. Now, once x* is inlined,
616 -- the occurrences of x' will be just the occurrences originally
619 returnSmpl (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tyvars_here))
621 mk_silly_bind var rhs = NonRec var (Note InlineMe rhs)
622 -- Suppose we start with:
624 -- x = /\ a -> let g = G in E
626 -- Then we'll float to get
628 -- x = let poly_g = /\ a -> G
629 -- in /\ a -> let g = poly_g a in E
631 -- But now the occurrence analyser will see just one occurrence
632 -- of poly_g, not inside a lambda, so the simplifier will
633 -- PreInlineUnconditionally poly_g back into g! Badk to square 1!
634 -- (I used to think that the "don't inline lone occurrences" stuff
635 -- would stop this happening, but since it's the *only* occurrence,
636 -- PreInlineUnconditionally kicks in first!)
638 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
639 -- to appear many times. (NB: mkInlineMe eliminates
640 -- such notes on trivial RHSs, so do it manually.)
644 %************************************************************************
646 \subsection{Eta expansion}
648 %************************************************************************
650 Try eta expansion for RHSs
653 Case 1 f = \x1..xn -> N ==> f = \x1..xn y1..ym -> N y1..ym
656 Case 2 f = N E1..En ==> z1=E1
659 f = \y1..ym -> N z1..zn y1..ym
661 where (in both cases)
663 * The xi can include type variables
665 * The yi are all value variables
667 * N is a NORMAL FORM (i.e. no redexes anywhere)
668 wanting a suitable number of extra args.
670 * the Ei must not have unlifted type
672 There is no point in looking for a combination of the two, because
673 that would leave use with some lets sandwiched between lambdas; that's
674 what the final test in the first equation is for.
676 In Case 1, we may have to sandwich some coerces between the lambdas
677 to make the types work. exprEtaExpandArity looks through coerces
678 when computing arity; and etaExpand adds the coerces as necessary when
679 actually computing the expansion.
682 tryEtaExpansion :: OutExpr -> OutType -> SimplM ([OutBind], OutExpr)
683 tryEtaExpansion rhs rhs_ty
684 | not opt_SimplDoLambdaEtaExpansion -- Not if switched off
685 || exprIsTrivial rhs -- Not if RHS is trivial
686 || final_arity == 0 -- Not if arity is zero
687 = returnSmpl ([], rhs)
689 | n_val_args == 0 && not arity_is_manifest
690 = -- Some lambdas but not enough: case 1
691 getUniqSupplySmpl `thenSmpl` \ us ->
692 returnSmpl ([], etaExpand final_arity us rhs rhs_ty)
694 | n_val_args > 0 && not (any cant_bind arg_infos)
695 = -- Partial application: case 2
696 mapAndUnzipSmpl bind_z_arg arg_infos `thenSmpl` \ (maybe_z_binds, z_args) ->
697 getUniqSupplySmpl `thenSmpl` \ us ->
698 returnSmpl (catMaybes maybe_z_binds,
699 etaExpand final_arity us (mkApps fun z_args) rhs_ty)
702 = returnSmpl ([], rhs)
704 (fun, args) = collectArgs rhs
705 n_val_args = valArgCount args
706 (fun_arity, arity_is_manifest) = exprEtaExpandArity fun
707 final_arity = 0 `max` (fun_arity - n_val_args)
708 arg_infos = [(arg, exprType arg, exprIsTrivial arg) | arg <- args]
709 cant_bind (_, ty, triv) = not triv && isUnLiftedType ty
711 bind_z_arg (arg, arg_ty, trivial_arg)
712 | trivial_arg = returnSmpl (Nothing, arg)
713 | otherwise = newId SLIT("z") arg_ty $ \ z ->
714 returnSmpl (Just (NonRec z arg), Var z)
718 %************************************************************************
720 \subsection{Case absorption and identity-case elimination}
722 %************************************************************************
725 mkCase :: OutExpr -> OutId -> [OutAlt] -> SimplM OutExpr
728 @mkCase@ tries the following transformation (if possible):
730 case e of b { ==> case e of b {
731 p1 -> rhs1 p1 -> rhs1
733 pm -> rhsm pm -> rhsm
734 _ -> case b of b' { pn -> rhsn[b/b'] {or (alg) let b=b' in rhsn}
735 {or (prim) case b of b' { _ -> rhsn}}
738 po -> rhso _ -> rhsd[b/b'] {or let b'=b in rhsd}
742 which merges two cases in one case when -- the default alternative of
743 the outer case scrutises the same variable as the outer case This
744 transformation is called Case Merging. It avoids that the same
745 variable is scrutinised multiple times.
748 mkCase scrut outer_bndr outer_alts
750 && maybeToBool maybe_case_in_default
752 = tick (CaseMerge outer_bndr) `thenSmpl_`
753 returnSmpl (Case scrut outer_bndr new_alts)
754 -- Warning: don't call mkCase recursively!
755 -- Firstly, there's no point, because inner alts have already had
756 -- mkCase applied to them, so they won't have a case in their default
757 -- Secondly, if you do, you get an infinite loop, because the bindNonRec
758 -- in munge_rhs puts a case into the DEFAULT branch!
760 new_alts = add_default maybe_inner_default
761 (outer_alts_without_deflt ++ inner_con_alts)
763 maybe_case_in_default = case findDefault outer_alts of
764 (outer_alts_without_default,
765 Just (Case (Var scrut_var) inner_bndr inner_alts))
766 | outer_bndr == scrut_var
767 -> Just (outer_alts_without_default, inner_bndr, inner_alts)
770 Just (outer_alts_without_deflt, inner_bndr, inner_alts) = maybe_case_in_default
772 -- Eliminate any inner alts which are shadowed by the outer ones
773 outer_cons = [con | (con,_,_) <- outer_alts_without_deflt]
775 munged_inner_alts = [ (con, args, munge_rhs rhs)
776 | (con, args, rhs) <- inner_alts,
777 not (con `elem` outer_cons) -- Eliminate shadowed inner alts
779 munge_rhs rhs = bindNonRec inner_bndr (Var outer_bndr) rhs
781 (inner_con_alts, maybe_inner_default) = findDefault munged_inner_alts
783 add_default (Just rhs) alts = (DEFAULT,[],rhs) : alts
784 add_default Nothing alts = alts
787 Now the identity-case transformation:
796 mkCase scrut case_bndr alts
797 | all identity_alt alts
798 = tick (CaseIdentity case_bndr) `thenSmpl_`
799 returnSmpl (re_note scrut)
801 identity_alt (con, args, rhs) = de_note rhs `cheapEqExpr` identity_rhs con args
803 identity_rhs (DataAlt con) args = mkConApp con (arg_tys ++ map varToCoreExpr args)
804 identity_rhs (LitAlt lit) _ = Lit lit
805 identity_rhs DEFAULT _ = Var case_bndr
807 arg_tys = map Type (tyConAppArgs (idType case_bndr))
810 -- case coerce T e of x { _ -> coerce T' x }
811 -- And we definitely want to eliminate this case!
812 -- So we throw away notes from the RHS, and reconstruct
813 -- (at least an approximation) at the other end
814 de_note (Note _ e) = de_note e
817 -- re_note wraps a coerce if it might be necessary
818 re_note scrut = case head alts of
819 (_,_,rhs1@(Note _ _)) -> mkCoerce (exprType rhs1) (idType case_bndr) scrut
823 The catch-all case. We do a final transformation that I've
824 occasionally seen making a big difference:
826 case e of =====> case e of
827 C _ -> f x D v -> ....v....
828 D v -> ....v.... DEFAULT -> f x
831 The point is that we merge common RHSs, at least for the DEFAULT case.
832 [One could do something more elaborate but I've never seen it needed.]
833 The case where this came up was like this (lib/std/PrelCError.lhs):
839 where @is@ was something like
841 p `is` n = p /= (-1) && p == n
843 This gave rise to a horrible sequence of cases
850 and similarly in cascade for all the join points!
853 mkCase other_scrut case_bndr other_alts
854 = returnSmpl (Case other_scrut case_bndr (mergeDefault other_alts))
856 mergeDefault (deflt_alt@(DEFAULT,_,deflt_rhs) : con_alts)
857 = deflt_alt : [alt | alt@(con,_,rhs) <- con_alts, not (rhs `cheapEqExpr` deflt_rhs)]
858 -- NB: we can neglect the binders because we won't get equality if the
859 -- binders are mentioned in rhs (no shadowing)
860 mergeDefault other_alts