2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section[SimplUtils]{The simplifier utilities}
8 simplBinder, simplBinders, simplRecIds, simplLetId, simplLamBinders,
12 -- The continuation type
13 SimplCont(..), DupFlag(..), LetRhsFlag(..),
14 contIsDupable, contResultType,
15 countValArgs, countArgs,
16 mkBoringStop, mkStop, contIsRhs, contIsRhsOrArg,
17 getContArgs, interestingCallContext, interestingArg, isStrictType, discardInline
21 #include "HsVersions.h"
23 import CmdLineOpts ( SimplifierSwitch(..),
24 opt_SimplDoLambdaEtaExpansion, opt_SimplDoEtaReduction,
25 opt_SimplCaseMerge, opt_UF_UpdateInPlace
28 import CoreFVs ( exprSomeFreeVars, exprsSomeFreeVars )
29 import CoreUtils ( exprIsTrivial, cheapEqExpr, exprType, exprIsCheap,
30 etaExpand, exprEtaExpandArity, bindNonRec, mkCoerce,
31 findDefault, exprOkForSpeculation, exprIsValue
33 import Subst ( InScopeSet, mkSubst, substExpr )
34 import qualified Subst ( simplBndrs, simplBndr, simplLetId, simplLamBndr )
35 import Id ( Id, idType, idName,
36 mkSysLocal, hasNoBinding, isDeadBinder, idNewDemandInfo,
37 idUnfolding, idNewStrictness,
40 import Name ( setNameUnique )
41 import NewDemand ( isStrictDmd, isBotRes, splitStrictSig )
43 import Type ( Type, mkForAllTys, seqType,
44 splitTyConApp_maybe, tyConAppArgs, mkTyVarTys,
45 isUnLiftedType, splitRepFunTys, isStrictType
47 import OccName ( UserFS )
48 import TyCon ( tyConDataConsIfAvailable, isDataTyCon )
49 import DataCon ( dataConRepArity, dataConSig, dataConArgTys )
50 import Var ( mkSysTyVar, tyVarKind )
51 import VarEnv ( SubstEnv )
52 import VarSet ( mkVarSet, varSetElems, intersectVarSet )
53 import Util ( lengthExceeds, mapAccumL )
58 %************************************************************************
60 \subsection{The continuation data type}
62 %************************************************************************
65 data SimplCont -- Strict contexts
66 = Stop OutType -- Type of the result
68 Bool -- True <=> This is the RHS of a thunk whose type suggests
69 -- that update-in-place would be possible
70 -- (This makes the inliner a little keener.)
72 | CoerceIt OutType -- The To-type, simplified
75 | InlinePlease -- This continuation makes a function very
76 SimplCont -- keen to inline itelf
79 InExpr SimplEnv -- The argument, as yet unsimplified,
80 SimplCont -- and its environment
83 InId [InAlt] SimplEnv -- The case binder, alts, and subst-env
86 | ArgOf DupFlag -- An arbitrary strict context: the argument
87 -- of a strict function, or a primitive-arg fn
90 OutType -- cont_ty: the type of the expression being sought by the context
91 -- f (error "foo") ==> coerce t (error "foo")
93 -- We need to know the type t, to which to coerce.
94 (SimplEnv -> OutExpr -> SimplM FloatsWithExpr) -- What to do with the result
95 -- The result expression in the OutExprStuff has type cont_ty
97 data LetRhsFlag = AnArg -- It's just an argument not a let RHS
98 | AnRhs -- It's the RHS of a let (so please float lets out of big lambdas)
100 instance Outputable LetRhsFlag where
101 ppr AnArg = ptext SLIT("arg")
102 ppr AnRhs = ptext SLIT("rhs")
104 instance Outputable SimplCont where
105 ppr (Stop _ is_rhs _) = ptext SLIT("Stop") <> brackets (ppr is_rhs)
106 ppr (ApplyTo dup arg se cont) = (ptext SLIT("ApplyTo") <+> ppr dup <+> ppr arg) $$ ppr cont
107 ppr (ArgOf dup _ _ _) = ptext SLIT("ArgOf...") <+> ppr dup
108 ppr (Select dup bndr alts se cont) = (ptext SLIT("Select") <+> ppr dup <+> ppr bndr) $$
109 (nest 4 (ppr alts)) $$ ppr cont
110 ppr (CoerceIt ty cont) = (ptext SLIT("CoerceIt") <+> ppr ty) $$ ppr cont
111 ppr (InlinePlease cont) = ptext SLIT("InlinePlease") $$ ppr cont
113 data DupFlag = OkToDup | NoDup
115 instance Outputable DupFlag where
116 ppr OkToDup = ptext SLIT("ok")
117 ppr NoDup = ptext SLIT("nodup")
121 mkBoringStop :: OutType -> SimplCont
122 mkBoringStop ty = Stop ty AnArg (canUpdateInPlace ty)
124 mkStop :: OutType -> LetRhsFlag -> SimplCont
125 mkStop ty is_rhs = Stop ty is_rhs (canUpdateInPlace ty)
127 contIsRhs :: SimplCont -> Bool
128 contIsRhs (Stop _ AnRhs _) = True
129 contIsRhs (ArgOf _ AnRhs _ _) = True
130 contIsRhs other = False
132 contIsRhsOrArg (Stop _ _ _) = True
133 contIsRhsOrArg (ArgOf _ _ _ _) = True
134 contIsRhsOrArg other = False
137 contIsDupable :: SimplCont -> Bool
138 contIsDupable (Stop _ _ _) = True
139 contIsDupable (ApplyTo OkToDup _ _ _) = True
140 contIsDupable (ArgOf OkToDup _ _ _) = True
141 contIsDupable (Select OkToDup _ _ _ _) = True
142 contIsDupable (CoerceIt _ cont) = contIsDupable cont
143 contIsDupable (InlinePlease cont) = contIsDupable cont
144 contIsDupable other = False
147 discardInline :: SimplCont -> SimplCont
148 discardInline (InlinePlease cont) = cont
149 discardInline (ApplyTo d e s cont) = ApplyTo d e s (discardInline cont)
150 discardInline cont = cont
153 discardableCont :: SimplCont -> Bool
154 discardableCont (Stop _ _ _) = False
155 discardableCont (CoerceIt _ cont) = discardableCont cont
156 discardableCont (InlinePlease cont) = discardableCont cont
157 discardableCont other = True
159 discardCont :: SimplCont -- A continuation, expecting
160 -> SimplCont -- Replace the continuation with a suitable coerce
161 discardCont cont = case cont of
162 Stop to_ty is_rhs _ -> cont
163 other -> CoerceIt to_ty (mkBoringStop to_ty)
165 to_ty = contResultType cont
168 contResultType :: SimplCont -> OutType
169 contResultType (Stop to_ty _ _) = to_ty
170 contResultType (ArgOf _ _ to_ty _) = to_ty
171 contResultType (ApplyTo _ _ _ cont) = contResultType cont
172 contResultType (CoerceIt _ cont) = contResultType cont
173 contResultType (InlinePlease cont) = contResultType cont
174 contResultType (Select _ _ _ _ cont) = contResultType cont
177 countValArgs :: SimplCont -> Int
178 countValArgs (ApplyTo _ (Type ty) se cont) = countValArgs cont
179 countValArgs (ApplyTo _ val_arg se cont) = 1 + countValArgs cont
180 countValArgs other = 0
182 countArgs :: SimplCont -> Int
183 countArgs (ApplyTo _ arg se cont) = 1 + countArgs cont
189 getContArgs :: SwitchChecker
190 -> OutId -> SimplCont
191 -> ([(InExpr, SimplEnv, Bool)], -- Arguments; the Bool is true for strict args
192 SimplCont, -- Remaining continuation
193 Bool) -- Whether we came across an InlineCall
194 -- getContArgs id k = (args, k', inl)
195 -- args are the leading ApplyTo items in k
196 -- (i.e. outermost comes first)
197 -- augmented with demand info from the functionn
198 getContArgs chkr fun orig_cont
200 -- Ignore strictness info if the no-case-of-case
201 -- flag is on. Strictness changes evaluation order
202 -- and that can change full laziness
203 stricts | switchIsOn chkr NoCaseOfCase = vanilla_stricts
204 | otherwise = computed_stricts
206 go [] stricts False orig_cont
208 ----------------------------
211 go acc ss inl (ApplyTo _ arg@(Type _) se cont)
212 = go ((arg,se,False) : acc) ss inl cont
213 -- NB: don't bother to instantiate the function type
216 go acc (s:ss) inl (ApplyTo _ arg se cont)
217 = go ((arg,se,s) : acc) ss inl cont
219 -- An Inline continuation
220 go acc ss inl (InlinePlease cont)
221 = go acc ss True cont
223 -- We're run out of arguments, or else we've run out of demands
224 -- The latter only happens if the result is guaranteed bottom
225 -- This is the case for
226 -- * case (error "hello") of { ... }
227 -- * (error "Hello") arg
228 -- * f (error "Hello") where f is strict
231 | null ss && discardableCont cont = (reverse acc, discardCont cont, inl)
232 | otherwise = (reverse acc, cont, inl)
234 ----------------------------
235 vanilla_stricts, computed_stricts :: [Bool]
236 vanilla_stricts = repeat False
237 computed_stricts = zipWith (||) fun_stricts arg_stricts
239 ----------------------------
240 (val_arg_tys, _) = splitRepFunTys (idType fun)
241 arg_stricts = map isStrictType val_arg_tys ++ repeat False
242 -- These argument types are used as a cheap and cheerful way to find
243 -- unboxed arguments, which must be strict. But it's an InType
244 -- and so there might be a type variable where we expect a function
245 -- type (the substitution hasn't happened yet). And we don't bother
246 -- doing the type applications for a polymorphic function.
247 -- Hence the split*Rep*FunTys
249 ----------------------------
250 -- If fun_stricts is finite, it means the function returns bottom
251 -- after that number of value args have been consumed
252 -- Otherwise it's infinite, extended with False
254 = case splitStrictSig (idNewStrictness fun) of
255 (demands, result_info)
256 | not (demands `lengthExceeds` countValArgs orig_cont)
257 -> -- Enough args, use the strictness given.
258 -- For bottoming functions we used to pretend that the arg
259 -- is lazy, so that we don't treat the arg as an
260 -- interesting context. This avoids substituting
261 -- top-level bindings for (say) strings into
262 -- calls to error. But now we are more careful about
263 -- inlining lone variables, so its ok (see SimplUtils.analyseCont)
264 if isBotRes result_info then
265 map isStrictDmd demands -- Finite => result is bottom
267 map isStrictDmd demands ++ vanilla_stricts
269 other -> vanilla_stricts -- Not enough args, or no strictness
272 interestingArg :: InScopeSet -> InExpr -> SubstEnv -> Bool
273 -- An argument is interesting if it has *some* structure
274 -- We are here trying to avoid unfolding a function that
275 -- is applied only to variables that have no unfolding
276 -- (i.e. they are probably lambda bound): f x y z
277 -- There is little point in inlining f here.
278 interestingArg in_scope arg subst
279 = analyse (substExpr (mkSubst in_scope subst) arg)
280 -- 'analyse' only looks at the top part of the result
281 -- and substExpr is lazy, so this isn't nearly as brutal
284 analyse (Var v) = hasSomeUnfolding (idUnfolding v)
285 -- Was: isValueUnfolding (idUnfolding v')
286 -- But that seems over-pessimistic
287 analyse (Type _) = False
288 analyse (App fn (Type _)) = analyse fn
289 analyse (Note _ a) = analyse a
291 -- Consider let x = 3 in f x
292 -- The substitution will contain (x -> ContEx 3), and we want to
293 -- to say that x is an interesting argument.
294 -- But consider also (\x. f x y) y
295 -- The substitution will contain (x -> ContEx y), and we want to say
296 -- that x is not interesting (assuming y has no unfolding)
299 Comment about interestingCallContext
300 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
301 We want to avoid inlining an expression where there can't possibly be
302 any gain, such as in an argument position. Hence, if the continuation
303 is interesting (eg. a case scrutinee, application etc.) then we
304 inline, otherwise we don't.
306 Previously some_benefit used to return True only if the variable was
307 applied to some value arguments. This didn't work:
309 let x = _coerce_ (T Int) Int (I# 3) in
310 case _coerce_ Int (T Int) x of
313 we want to inline x, but can't see that it's a constructor in a case
314 scrutinee position, and some_benefit is False.
318 dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t)
320 .... case dMonadST _@_ x0 of (a,b,c) -> ....
322 we'd really like to inline dMonadST here, but we *don't* want to
323 inline if the case expression is just
325 case x of y { DEFAULT -> ... }
327 since we can just eliminate this case instead (x is in WHNF). Similar
328 applies when x is bound to a lambda expression. Hence
329 contIsInteresting looks for case expressions with just a single
333 interestingCallContext :: Bool -- False <=> no args at all
334 -> Bool -- False <=> no value args
336 -- The "lone-variable" case is important. I spent ages
337 -- messing about with unsatisfactory varaints, but this is nice.
338 -- The idea is that if a variable appear all alone
339 -- as an arg of lazy fn, or rhs Stop
340 -- as scrutinee of a case Select
341 -- as arg of a strict fn ArgOf
342 -- then we should not inline it (unless there is some other reason,
343 -- e.g. is is the sole occurrence). We achieve this by making
344 -- interestingCallContext return False for a lone variable.
346 -- Why? At least in the case-scrutinee situation, turning
347 -- let x = (a,b) in case x of y -> ...
349 -- let x = (a,b) in case (a,b) of y -> ...
351 -- let x = (a,b) in let y = (a,b) in ...
352 -- is bad if the binding for x will remain.
354 -- Another example: I discovered that strings
355 -- were getting inlined straight back into applications of 'error'
356 -- because the latter is strict.
358 -- f = \x -> ...(error s)...
360 -- Fundamentally such contexts should not ecourage inlining because
361 -- the context can ``see'' the unfolding of the variable (e.g. case or a RULE)
362 -- so there's no gain.
364 -- However, even a type application or coercion isn't a lone variable.
366 -- case $fMonadST @ RealWorld of { :DMonad a b c -> c }
367 -- We had better inline that sucker! The case won't see through it.
369 -- For now, I'm treating treating a variable applied to types
370 -- in a *lazy* context "lone". The motivating example was
372 -- g = /\a. \y. h (f a)
373 -- There's no advantage in inlining f here, and perhaps
374 -- a significant disadvantage. Hence some_val_args in the Stop case
376 interestingCallContext some_args some_val_args cont
379 interesting (InlinePlease _) = True
380 interesting (Select _ _ _ _ _) = some_args
381 interesting (ApplyTo _ _ _ _) = True -- Can happen if we have (coerce t (f x)) y
382 -- Perhaps True is a bit over-keen, but I've
383 -- seen (coerce f) x, where f has an INLINE prag,
384 -- So we have to give some motivaiton for inlining it
385 interesting (ArgOf _ _ _ _) = some_val_args
386 interesting (Stop ty _ upd_in_place) = some_val_args && upd_in_place
387 interesting (CoerceIt _ cont) = interesting cont
388 -- If this call is the arg of a strict function, the context
389 -- is a bit interesting. If we inline here, we may get useful
390 -- evaluation information to avoid repeated evals: e.g.
392 -- Here the contIsInteresting makes the '*' keener to inline,
393 -- which in turn exposes a constructor which makes the '+' inline.
394 -- Assuming that +,* aren't small enough to inline regardless.
396 -- It's also very important to inline in a strict context for things
399 -- Here, the context of (f x) is strict, and if f's unfolding is
400 -- a build it's *great* to inline it here. So we must ensure that
401 -- the context for (f x) is not totally uninteresting.
405 canUpdateInPlace :: Type -> Bool
406 -- Consider let x = <wurble> in ...
407 -- If <wurble> returns an explicit constructor, we might be able
408 -- to do update in place. So we treat even a thunk RHS context
409 -- as interesting if update in place is possible. We approximate
410 -- this by seeing if the type has a single constructor with a
411 -- small arity. But arity zero isn't good -- we share the single copy
412 -- for that case, so no point in sharing.
415 | not opt_UF_UpdateInPlace = False
417 = case splitTyConApp_maybe ty of
419 Just (tycon, _) -> case tyConDataConsIfAvailable tycon of
420 [dc] -> arity == 1 || arity == 2
422 arity = dataConRepArity dc
428 %************************************************************************
430 \section{Dealing with a single binder}
432 %************************************************************************
434 These functions are in the monad only so that they can be made strict via seq.
437 simplBinders :: SimplEnv -> [InBinder] -> SimplM (SimplEnv, [OutBinder])
438 simplBinders env bndrs
440 (subst', bndrs') = Subst.simplBndrs (getSubst env) bndrs
442 seqBndrs bndrs' `seq`
443 returnSmpl (setSubst env subst', bndrs')
445 simplBinder :: SimplEnv -> InBinder -> SimplM (SimplEnv, OutBinder)
448 (subst', bndr') = Subst.simplBndr (getSubst env) bndr
451 returnSmpl (setSubst env subst', bndr')
454 simplLamBinders :: SimplEnv -> [InBinder] -> SimplM (SimplEnv, [OutBinder])
455 simplLamBinders env bndrs
457 (subst', bndrs') = mapAccumL Subst.simplLamBndr (getSubst env) bndrs
459 seqBndrs bndrs' `seq`
460 returnSmpl (setSubst env subst', bndrs')
462 simplRecIds :: SimplEnv -> [InBinder] -> SimplM (SimplEnv, [OutBinder])
465 (subst', ids') = mapAccumL Subst.simplLetId (getSubst env) ids
468 returnSmpl (setSubst env subst', ids')
470 simplLetId :: SimplEnv -> InBinder -> SimplM (SimplEnv, OutBinder)
473 (subst', id') = Subst.simplLetId (getSubst env) id
476 returnSmpl (setSubst env subst', id')
479 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
481 seqBndr b | isTyVar b = b `seq` ()
482 | otherwise = seqType (idType b) `seq`
489 newId :: UserFS -> Type -> SimplM Id
490 newId fs ty = getUniqueSmpl `thenSmpl` \ uniq ->
491 returnSmpl (mkSysLocal fs uniq ty)
495 %************************************************************************
497 \subsection{Rebuilding a lambda}
499 %************************************************************************
502 mkLam :: SimplEnv -> [OutBinder] -> OutExpr -> SimplCont -> SimplM FloatsWithExpr
506 a) eta reduction, if that gives a trivial expression
507 b) eta expansion [only if there are some value lambdas]
508 c) floating lets out through big lambdas
509 [only if all tyvar lambdas, and only if this lambda
513 mkLam env bndrs body cont
514 | opt_SimplDoEtaReduction,
515 Just etad_lam <- tryEtaReduce bndrs body
516 = tick (EtaReduction (head bndrs)) `thenSmpl_`
517 returnSmpl (emptyFloats env, etad_lam)
519 | opt_SimplDoLambdaEtaExpansion,
520 any isRuntimeVar bndrs
521 = tryEtaExpansion body `thenSmpl` \ body' ->
522 returnSmpl (emptyFloats env, mkLams bndrs body')
524 {- Sept 01: I'm experimenting with getting the
525 full laziness pass to float out past big lambdsa
526 | all isTyVar bndrs, -- Only for big lambdas
527 contIsRhs cont -- Only try the rhs type-lambda floating
528 -- if this is indeed a right-hand side; otherwise
529 -- we end up floating the thing out, only for float-in
530 -- to float it right back in again!
531 = tryRhsTyLam env bndrs body `thenSmpl` \ (floats, body') ->
532 returnSmpl (floats, mkLams bndrs body')
536 = returnSmpl (emptyFloats env, mkLams bndrs body)
540 %************************************************************************
542 \subsection{Eta expansion and reduction}
544 %************************************************************************
546 We try for eta reduction here, but *only* if we get all the
547 way to an exprIsTrivial expression.
548 We don't want to remove extra lambdas unless we are going
549 to avoid allocating this thing altogether
552 tryEtaReduce :: [OutBinder] -> OutExpr -> Maybe OutExpr
553 tryEtaReduce bndrs body
554 -- We don't use CoreUtils.etaReduce, because we can be more
556 -- (a) we already have the binders
557 -- (b) we can do the triviality test before computing the free vars
558 -- [in fact I take the simple path and look for just a variable]
559 = go (reverse bndrs) body
561 go (b : bs) (App fun arg) | ok_arg b arg = go bs fun -- Loop round
562 go [] (Var fun) | ok_fun fun = Just (Var fun) -- Success!
563 go _ _ = Nothing -- Failure!
565 ok_fun fun = not (fun `elem` bndrs) && not (hasNoBinding fun)
566 ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
570 Try eta expansion for RHSs
573 f = \x1..xn -> N ==> f = \x1..xn y1..ym -> N y1..ym
576 where (in both cases)
578 * The xi can include type variables
580 * The yi are all value variables
582 * N is a NORMAL FORM (i.e. no redexes anywhere)
583 wanting a suitable number of extra args.
585 We may have to sandwich some coerces between the lambdas
586 to make the types work. exprEtaExpandArity looks through coerces
587 when computing arity; and etaExpand adds the coerces as necessary when
588 actually computing the expansion.
591 tryEtaExpansion :: OutExpr -> SimplM OutExpr
592 -- There is at least one runtime binder in the binders
594 | arity_is_manifest -- Some lambdas but not enough
598 = getUniquesSmpl `thenSmpl` \ us ->
599 returnSmpl (etaExpand fun_arity us body (exprType body))
601 (fun_arity, arity_is_manifest) = exprEtaExpandArity body
605 %************************************************************************
607 \subsection{Floating lets out of big lambdas}
609 %************************************************************************
611 tryRhsTyLam tries this transformation, when the big lambda appears as
612 the RHS of a let(rec) binding:
614 /\abc -> let(rec) x = e in b
616 let(rec) x' = /\abc -> let x = x' a b c in e
618 /\abc -> let x = x' a b c in b
620 This is good because it can turn things like:
622 let f = /\a -> letrec g = ... g ... in g
624 letrec g' = /\a -> ... g' a ...
628 which is better. In effect, it means that big lambdas don't impede
631 This optimisation is CRUCIAL in eliminating the junk introduced by
632 desugaring mutually recursive definitions. Don't eliminate it lightly!
634 So far as the implementation is concerned:
636 Invariant: go F e = /\tvs -> F e
640 = Let x' = /\tvs -> F e
644 G = F . Let x = x' tvs
646 go F (Letrec xi=ei in b)
647 = Letrec {xi' = /\tvs -> G ei}
651 G = F . Let {xi = xi' tvs}
653 [May 1999] If we do this transformation *regardless* then we can
654 end up with some pretty silly stuff. For example,
657 st = /\ s -> let { x1=r1 ; x2=r2 } in ...
662 st = /\s -> ...[y1 s/x1, y2 s/x2]
665 Unless the "..." is a WHNF there is really no point in doing this.
666 Indeed it can make things worse. Suppose x1 is used strictly,
669 x1* = case f y of { (a,b) -> e }
671 If we abstract this wrt the tyvar we then can't do the case inline
672 as we would normally do.
676 {- Trying to do this in full laziness
678 tryRhsTyLam :: SimplEnv -> [OutTyVar] -> OutExpr -> SimplM FloatsWithExpr
679 -- Call ensures that all the binders are type variables
681 tryRhsTyLam env tyvars body -- Only does something if there's a let
682 | not (all isTyVar tyvars)
683 || not (worth_it body) -- inside a type lambda,
684 = returnSmpl (emptyFloats env, body) -- and a WHNF inside that
687 = go env (\x -> x) body
690 worth_it e@(Let _ _) = whnf_in_middle e
693 whnf_in_middle (Let (NonRec x rhs) e) | isUnLiftedType (idType x) = False
694 whnf_in_middle (Let _ e) = whnf_in_middle e
695 whnf_in_middle e = exprIsCheap e
697 main_tyvar_set = mkVarSet tyvars
699 go env fn (Let bind@(NonRec var rhs) body)
701 = go env (fn . Let bind) body
703 go env fn (Let (NonRec var rhs) body)
704 = mk_poly tyvars_here var `thenSmpl` \ (var', rhs') ->
705 addAuxiliaryBind env (NonRec var' (mkLams tyvars_here (fn rhs))) $ \ env ->
706 go env (fn . Let (mk_silly_bind var rhs')) body
710 tyvars_here = varSetElems (main_tyvar_set `intersectVarSet` exprSomeFreeVars isTyVar rhs)
711 -- Abstract only over the type variables free in the rhs
712 -- wrt which the new binding is abstracted. But the naive
713 -- approach of abstract wrt the tyvars free in the Id's type
715 -- /\ a b -> let t :: (a,b) = (e1, e2)
718 -- Here, b isn't free in x's type, but we must nevertheless
719 -- abstract wrt b as well, because t's type mentions b.
720 -- Since t is floated too, we'd end up with the bogus:
721 -- poly_t = /\ a b -> (e1, e2)
722 -- poly_x = /\ a -> fst (poly_t a *b*)
723 -- So for now we adopt the even more naive approach of
724 -- abstracting wrt *all* the tyvars. We'll see if that
725 -- gives rise to problems. SLPJ June 98
727 go env fn (Let (Rec prs) body)
728 = mapAndUnzipSmpl (mk_poly tyvars_here) vars `thenSmpl` \ (vars', rhss') ->
730 gn body = fn (foldr Let body (zipWith mk_silly_bind vars rhss'))
731 pairs = vars' `zip` [mkLams tyvars_here (gn rhs) | rhs <- rhss]
733 addAuxiliaryBind env (Rec pairs) $ \ env ->
736 (vars,rhss) = unzip prs
737 tyvars_here = varSetElems (main_tyvar_set `intersectVarSet` exprsSomeFreeVars isTyVar (map snd prs))
738 -- See notes with tyvars_here above
740 go env fn body = returnSmpl (emptyFloats env, fn body)
742 mk_poly tyvars_here var
743 = getUniqueSmpl `thenSmpl` \ uniq ->
745 poly_name = setNameUnique (idName var) uniq -- Keep same name
746 poly_ty = mkForAllTys tyvars_here (idType var) -- But new type of course
747 poly_id = mkLocalId poly_name poly_ty
749 -- In the olden days, it was crucial to copy the occInfo of the original var,
750 -- because we were looking at occurrence-analysed but as yet unsimplified code!
751 -- In particular, we mustn't lose the loop breakers. BUT NOW we are looking
752 -- at already simplified code, so it doesn't matter
754 -- It's even right to retain single-occurrence or dead-var info:
755 -- Suppose we started with /\a -> let x = E in B
756 -- where x occurs once in B. Then we transform to:
757 -- let x' = /\a -> E in /\a -> let x* = x' a in B
758 -- where x* has an INLINE prag on it. Now, once x* is inlined,
759 -- the occurrences of x' will be just the occurrences originally
762 returnSmpl (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tyvars_here))
764 mk_silly_bind var rhs = NonRec var (Note InlineMe rhs)
765 -- Suppose we start with:
767 -- x = /\ a -> let g = G in E
769 -- Then we'll float to get
771 -- x = let poly_g = /\ a -> G
772 -- in /\ a -> let g = poly_g a in E
774 -- But now the occurrence analyser will see just one occurrence
775 -- of poly_g, not inside a lambda, so the simplifier will
776 -- PreInlineUnconditionally poly_g back into g! Badk to square 1!
777 -- (I used to think that the "don't inline lone occurrences" stuff
778 -- would stop this happening, but since it's the *only* occurrence,
779 -- PreInlineUnconditionally kicks in first!)
781 -- Solution: put an INLINE note on g's RHS, so that poly_g seems
782 -- to appear many times. (NB: mkInlineMe eliminates
783 -- such notes on trivial RHSs, so do it manually.)
788 %************************************************************************
790 \subsection{Case absorption and identity-case elimination}
792 %************************************************************************
794 mkCase puts a case expression back together, trying various transformations first.
797 mkCase :: OutExpr -> OutId -> [OutAlt] -> SimplM OutExpr
799 mkCase scrut case_bndr alts
800 = mkAlts scrut case_bndr alts `thenSmpl` \ better_alts ->
801 mkCase1 scrut case_bndr better_alts
805 mkAlts tries these things:
807 1. If several alternatives are identical, merge them into
808 a single DEFAULT alternative. I've occasionally seen this
809 making a big difference:
811 case e of =====> case e of
812 C _ -> f x D v -> ....v....
813 D v -> ....v.... DEFAULT -> f x
816 The point is that we merge common RHSs, at least for the DEFAULT case.
817 [One could do something more elaborate but I've never seen it needed.]
818 To avoid an expensive test, we just merge branches equal to the *first*
819 alternative; this picks up the common cases
820 a) all branches equal
821 b) some branches equal to the DEFAULT (which occurs first)
823 2. If the DEFAULT alternative can match only one possible constructor,
824 then make that constructor explicit.
826 case e of x { DEFAULT -> rhs }
828 case e of x { (a,b) -> rhs }
829 where the type is a single constructor type. This gives better code
830 when rhs also scrutinises x or e.
833 case e of b { ==> case e of b {
834 p1 -> rhs1 p1 -> rhs1
836 pm -> rhsm pm -> rhsm
837 _ -> case b of b' { pn -> let b'=b in rhsn
839 ... po -> let b'=b in rhso
840 po -> rhso _ -> let b'=b in rhsd
844 which merges two cases in one case when -- the default alternative of
845 the outer case scrutises the same variable as the outer case This
846 transformation is called Case Merging. It avoids that the same
847 variable is scrutinised multiple times.
850 The case where transformation (1) showed up was like this (lib/std/PrelCError.lhs):
856 where @is@ was something like
858 p `is` n = p /= (-1) && p == n
860 This gave rise to a horrible sequence of cases
867 and similarly in cascade for all the join points!
872 --------------------------------------------------
873 -- 1. Merge identical branches
874 --------------------------------------------------
875 mkAlts scrut case_bndr alts@((con1,bndrs1,rhs1) : con_alts)
876 | all isDeadBinder bndrs1, -- Remember the default
877 length filtered_alts < length con_alts -- alternative comes first
878 = tick (AltMerge case_bndr) `thenSmpl_`
879 returnSmpl better_alts
881 filtered_alts = filter keep con_alts
882 keep (con,bndrs,rhs) = not (all isDeadBinder bndrs && rhs `cheapEqExpr` rhs1)
883 better_alts = (DEFAULT, [], rhs1) : filtered_alts
886 --------------------------------------------------
887 -- 2. Fill in missing constructor
888 --------------------------------------------------
890 mkAlts scrut case_bndr alts
891 | Just (tycon, inst_tys) <- splitTyConApp_maybe (idType case_bndr),
892 isDataTyCon tycon, -- It's a data type
893 (alts_no_deflt, Just rhs) <- findDefault alts,
894 -- There is a DEFAULT case
895 [missing_con] <- filter is_missing (tyConDataConsIfAvailable tycon)
896 -- There is just one missing constructor!
897 = tick (FillInCaseDefault case_bndr) `thenSmpl_`
898 getUniquesSmpl `thenSmpl` \ tv_uniqs ->
899 getUniquesSmpl `thenSmpl` \ id_uniqs ->
901 (_,_,ex_tyvars,_,_,_) = dataConSig missing_con
902 ex_tyvars' = zipWith mk tv_uniqs ex_tyvars
903 mk uniq tv = mkSysTyVar uniq (tyVarKind tv)
904 arg_ids = zipWith (mkSysLocal SLIT("a")) id_uniqs arg_tys
905 arg_tys = dataConArgTys missing_con (inst_tys ++ mkTyVarTys ex_tyvars')
906 better_alts = (DataAlt missing_con, ex_tyvars' ++ arg_ids, rhs) : alts_no_deflt
908 returnSmpl better_alts
910 impossible_cons = otherCons (idUnfolding case_bndr)
911 handled_data_cons = [data_con | DataAlt data_con <- impossible_cons] ++
912 [data_con | (DataAlt data_con, _, _) <- alts]
913 is_missing con = not (con `elem` handled_data_cons)
915 --------------------------------------------------
916 -- 3. Merge nested cases
917 --------------------------------------------------
919 mkAlts scrut outer_bndr outer_alts
920 | opt_SimplCaseMerge,
921 (outer_alts_without_deflt, maybe_outer_deflt) <- findDefault outer_alts,
922 Just (Case (Var scrut_var) inner_bndr inner_alts) <- maybe_outer_deflt,
923 scruting_same_var scrut_var
925 = let -- Eliminate any inner alts which are shadowed by the outer ones
926 outer_cons = [con | (con,_,_) <- outer_alts_without_deflt]
928 munged_inner_alts = [ (con, args, munge_rhs rhs)
929 | (con, args, rhs) <- inner_alts,
930 not (con `elem` outer_cons) -- Eliminate shadowed inner alts
932 munge_rhs rhs = bindCaseBndr inner_bndr (Var outer_bndr) rhs
934 (inner_con_alts, maybe_inner_default) = findDefault munged_inner_alts
936 new_alts = add_default maybe_inner_default
937 (outer_alts_without_deflt ++ inner_con_alts)
939 tick (CaseMerge outer_bndr) `thenSmpl_`
941 -- Warning: don't call mkAlts recursively!
942 -- Firstly, there's no point, because inner alts have already had
943 -- mkCase applied to them, so they won't have a case in their default
944 -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr
945 -- in munge_rhs may put a case into the DEFAULT branch!
947 -- We are scrutinising the same variable if it's
948 -- the outer case-binder, or if the outer case scrutinises a variable
949 -- (and it's the same). Testing both allows us not to replace the
950 -- outer scrut-var with the outer case-binder (Simplify.simplCaseBinder).
951 scruting_same_var = case scrut of
952 Var outer_scrut -> \ v -> v == outer_bndr || v == outer_scrut
953 other -> \ v -> v == outer_bndr
955 add_default (Just rhs) alts = (DEFAULT,[],rhs) : alts
956 add_default Nothing alts = alts
959 --------------------------------------------------
961 --------------------------------------------------
963 mkAlts scrut case_bndr other_alts = returnSmpl other_alts
968 =================================================================================
970 mkCase1 tries these things
972 1. Eliminate the case altogether if possible
983 Start with a simple situation:
985 case x# of ===> e[x#/y#]
988 (when x#, y# are of primitive type, of course). We can't (in general)
989 do this for algebraic cases, because we might turn bottom into
992 Actually, we generalise this idea to look for a case where we're
993 scrutinising a variable, and we know that only the default case can
998 other -> ...(case x of
1002 Here the inner case can be eliminated. This really only shows up in
1003 eliminating error-checking code.
1005 We also make sure that we deal with this very common case:
1010 Here we are using the case as a strict let; if x is used only once
1011 then we want to inline it. We have to be careful that this doesn't
1012 make the program terminate when it would have diverged before, so we
1014 - x is used strictly, or
1015 - e is already evaluated (it may so if e is a variable)
1017 Lastly, we generalise the transformation to handle this:
1023 We only do this for very cheaply compared r's (constructors, literals
1024 and variables). If pedantic bottoms is on, we only do it when the
1025 scrutinee is a PrimOp which can't fail.
1027 We do it *here*, looking at un-simplified alternatives, because we
1028 have to check that r doesn't mention the variables bound by the
1029 pattern in each alternative, so the binder-info is rather useful.
1031 So the case-elimination algorithm is:
1033 1. Eliminate alternatives which can't match
1035 2. Check whether all the remaining alternatives
1036 (a) do not mention in their rhs any of the variables bound in their pattern
1037 and (b) have equal rhss
1039 3. Check we can safely ditch the case:
1040 * PedanticBottoms is off,
1041 or * the scrutinee is an already-evaluated variable
1042 or * the scrutinee is a primop which is ok for speculation
1043 -- ie we want to preserve divide-by-zero errors, and
1044 -- calls to error itself!
1046 or * [Prim cases] the scrutinee is a primitive variable
1048 or * [Alg cases] the scrutinee is a variable and
1049 either * the rhs is the same variable
1050 (eg case x of C a b -> x ===> x)
1051 or * there is only one alternative, the default alternative,
1052 and the binder is used strictly in its scope.
1053 [NB this is helped by the "use default binder where
1054 possible" transformation; see below.]
1057 If so, then we can replace the case with one of the rhss.
1061 --------------------------------------------------
1062 -- 1. Eliminate the case altogether if poss
1063 --------------------------------------------------
1065 mkCase1 scrut case_bndr [(con,bndrs,rhs)]
1066 -- See if we can get rid of the case altogether
1067 -- See the extensive notes on case-elimination above
1068 -- mkCase made sure that if all the alternatives are equal,
1069 -- then there is now only one (DEFAULT) rhs
1070 | all isDeadBinder bndrs,
1072 -- Check that the scrutinee can be let-bound instead of case-bound
1073 exprOkForSpeculation scrut
1074 -- OK not to evaluate it
1075 -- This includes things like (==# a# b#)::Bool
1076 -- so that we simplify
1077 -- case ==# a# b# of { True -> x; False -> x }
1080 -- This particular example shows up in default methods for
1081 -- comparision operations (e.g. in (>=) for Int.Int32)
1082 || exprIsValue scrut -- It's already evaluated
1083 || var_demanded_later scrut -- It'll be demanded later
1085 -- || not opt_SimplPedanticBottoms) -- Or we don't care!
1086 -- We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1087 -- but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1088 -- its argument: case x of { y -> dataToTag# y }
1089 -- Here we must *not* discard the case, because dataToTag# just fetches the tag from
1090 -- the info pointer. So we'll be pedantic all the time, and see if that gives any
1092 = tick (CaseElim case_bndr) `thenSmpl_`
1093 returnSmpl (bindCaseBndr case_bndr scrut rhs)
1096 -- The case binder is going to be evaluated later,
1097 -- and the scrutinee is a simple variable
1098 var_demanded_later (Var v) = isStrictDmd (idNewDemandInfo case_bndr)
1099 var_demanded_later other = False
1102 --------------------------------------------------
1104 --------------------------------------------------
1106 mkCase1 scrut case_bndr alts -- Identity case
1107 | all identity_alt alts
1108 = tick (CaseIdentity case_bndr) `thenSmpl_`
1109 returnSmpl (re_note scrut)
1111 identity_alt (con, args, rhs) = de_note rhs `cheapEqExpr` identity_rhs con args
1113 identity_rhs (DataAlt con) args = mkConApp con (arg_tys ++ map varToCoreExpr args)
1114 identity_rhs (LitAlt lit) _ = Lit lit
1115 identity_rhs DEFAULT _ = Var case_bndr
1117 arg_tys = map Type (tyConAppArgs (idType case_bndr))
1120 -- case coerce T e of x { _ -> coerce T' x }
1121 -- And we definitely want to eliminate this case!
1122 -- So we throw away notes from the RHS, and reconstruct
1123 -- (at least an approximation) at the other end
1124 de_note (Note _ e) = de_note e
1127 -- re_note wraps a coerce if it might be necessary
1128 re_note scrut = case head alts of
1129 (_,_,rhs1@(Note _ _)) -> mkCoerce (exprType rhs1) (idType case_bndr) scrut
1133 --------------------------------------------------
1135 --------------------------------------------------
1136 mkCase1 scrut bndr alts = returnSmpl (Case scrut bndr alts)
1140 When adding auxiliary bindings for the case binder, it's worth checking if
1141 its dead, because it often is, and occasionally these mkCase transformations
1142 cascade rather nicely.
1145 bindCaseBndr bndr rhs body
1146 | isDeadBinder bndr = body
1147 | otherwise = bindNonRec bndr rhs body