2 % (c) The AQUA Project, Glasgow University, 1993-1998
4 \section[Simplify]{The main module of the simplifier}
7 module Simplify ( simplTopBinds, simplExpr ) where
9 #include "HsVersions.h"
11 import CmdLineOpts ( switchIsOn, opt_SimplDoEtaReduction,
12 opt_SimplNoPreInlining,
16 import SimplUtils ( mkCase, transformRhs, findAlt,
17 simplBinder, simplBinders, simplIds, findDefault,
18 SimplCont(..), DupFlag(..), mkStop, mkRhsStop,
19 contResultType, discardInline, countArgs, contIsDupable,
20 getContArgs, interestingCallContext, interestingArg, isStrictType
22 import Var ( mkSysTyVar, tyVarKind )
24 import VarSet ( elemVarSet )
25 import Id ( Id, idType, idInfo, isDataConId,
26 idUnfolding, setIdUnfolding, isExportedId, isDeadBinder,
27 idDemandInfo, setIdInfo,
28 idOccInfo, setIdOccInfo,
29 zapLamIdInfo, setOneShotLambda,
31 import IdInfo ( OccInfo(..), isDeadOcc, isLoopBreaker,
32 setArityInfo, unknownArity,
36 import Demand ( isStrict )
37 import DataCon ( dataConNumInstArgs, dataConRepStrictness,
38 dataConSig, dataConArgTys
41 import CoreFVs ( mustHaveLocalBinding, exprFreeVars )
42 import CoreUnfold ( mkOtherCon, mkUnfolding, otherCons,
45 import CoreUtils ( cheapEqExpr, exprIsDupable, exprIsTrivial,
46 exprIsConApp_maybe, mkPiType,
47 exprType, coreAltsType, exprIsValue, idAppIsCheap,
49 mkCoerce, mkSCC, mkInlineMe, mkAltExpr
51 import Rules ( lookupRule )
52 import CostCentre ( currentCCS )
53 import Type ( mkTyVarTys, isUnLiftedType, seqType,
54 mkFunTy, splitTyConApp_maybe, tyConAppArgs,
57 import Subst ( mkSubst, substTy,
58 isInScope, lookupIdSubst, substIdInfo
60 import TyCon ( isDataTyCon, tyConDataConsIfAvailable )
61 import TysPrim ( realWorldStatePrimTy )
62 import PrelInfo ( realWorldPrimId )
63 import Maybes ( maybeToBool )
64 import Util ( zipWithEqual )
69 The guts of the simplifier is in this module, but the driver
70 loop for the simplifier is in SimplCore.lhs.
73 -----------------------------------------
74 *** IMPORTANT NOTE ***
75 -----------------------------------------
76 The simplifier used to guarantee that the output had no shadowing, but
77 it does not do so any more. (Actually, it never did!) The reason is
78 documented with simplifyArgs.
83 %************************************************************************
87 %************************************************************************
90 simplTopBinds :: [InBind] -> SimplM [OutBind]
93 = -- Put all the top-level binders into scope at the start
94 -- so that if a transformation rule has unexpectedly brought
95 -- anything into scope, then we don't get a complaint about that.
96 -- It's rather as if the top-level binders were imported.
97 simplIds (bindersOfBinds binds) $ \ bndrs' ->
98 simpl_binds binds bndrs' `thenSmpl` \ (binds', _) ->
99 freeTick SimplifierDone `thenSmpl_`
103 -- We need to track the zapped top-level binders, because
104 -- they should have their fragile IdInfo zapped (notably occurrence info)
105 simpl_binds [] bs = ASSERT( null bs ) returnSmpl ([], panic "simplTopBinds corner")
106 simpl_binds (NonRec bndr rhs : binds) (b:bs) = simplLazyBind True bndr b rhs (simpl_binds binds bs)
107 simpl_binds (Rec pairs : binds) bs = simplRecBind True pairs (take n bs) (simpl_binds binds (drop n bs))
111 simplRecBind :: Bool -> [(InId, InExpr)] -> [OutId]
112 -> SimplM (OutStuff a) -> SimplM (OutStuff a)
113 simplRecBind top_lvl pairs bndrs' thing_inside
114 = go pairs bndrs' `thenSmpl` \ (binds', (binds'', res)) ->
115 returnSmpl (Rec (flattenBinds binds') : binds'', res)
117 go [] _ = thing_inside `thenSmpl` \ stuff ->
118 returnSmpl ([], stuff)
120 go ((bndr, rhs) : pairs) (bndr' : bndrs')
121 = simplLazyBind top_lvl bndr bndr' rhs (go pairs bndrs')
122 -- Don't float unboxed bindings out,
123 -- because we can't "rec" them
127 %************************************************************************
129 \subsection[Simplify-simplExpr]{The main function: simplExpr}
131 %************************************************************************
133 The reason for this OutExprStuff stuff is that we want to float *after*
134 simplifying a RHS, not before. If we do so naively we get quadratic
135 behaviour as things float out.
137 To see why it's important to do it after, consider this (real) example:
151 a -- Can't inline a this round, cos it appears twice
155 Each of the ==> steps is a round of simplification. We'd save a
156 whole round if we float first. This can cascade. Consider
161 let f = let d1 = ..d.. in \y -> e
165 in \x -> ...(\y ->e)...
167 Only in this second round can the \y be applied, and it
168 might do the same again.
172 simplExpr :: CoreExpr -> SimplM CoreExpr
173 simplExpr expr = getSubst `thenSmpl` \ subst ->
174 simplExprC expr (mkStop (substTy subst (exprType expr)))
175 -- The type in the Stop continuation is usually not used
176 -- It's only needed when discarding continuations after finding
177 -- a function that returns bottom.
178 -- Hence the lazy substitution
180 simplExprC :: CoreExpr -> SimplCont -> SimplM CoreExpr
181 -- Simplify an expression, given a continuation
183 simplExprC expr cont = simplExprF expr cont `thenSmpl` \ (floats, (_, body)) ->
184 returnSmpl (mkLets floats body)
186 simplExprF :: InExpr -> SimplCont -> SimplM OutExprStuff
187 -- Simplify an expression, returning floated binds
189 simplExprF (Var v) cont
192 simplExprF (Lit lit) (Select _ bndr alts se cont)
193 = knownCon (Lit lit) (LitAlt lit) [] bndr alts se cont
195 simplExprF (Lit lit) cont
196 = rebuild (Lit lit) cont
198 simplExprF (App fun arg) cont
199 = getSubstEnv `thenSmpl` \ se ->
200 simplExprF fun (ApplyTo NoDup arg se cont)
202 simplExprF (Case scrut bndr alts) cont
203 = getSubstEnv `thenSmpl` \ subst_env ->
204 getSwitchChecker `thenSmpl` \ chkr ->
205 if not (switchIsOn chkr NoCaseOfCase) then
206 -- Simplify the scrutinee with a Select continuation
207 simplExprF scrut (Select NoDup bndr alts subst_env cont)
210 -- If case-of-case is off, simply simplify the case expression
211 -- in a vanilla Stop context, and rebuild the result around it
212 simplExprC scrut (Select NoDup bndr alts subst_env
213 (mkStop (contResultType cont))) `thenSmpl` \ case_expr' ->
214 rebuild case_expr' cont
217 simplExprF (Let (Rec pairs) body) cont
218 = simplIds (map fst pairs) $ \ bndrs' ->
219 -- NB: bndrs' don't have unfoldings or spec-envs
220 -- We add them as we go down, using simplPrags
222 simplRecBind False pairs bndrs' (simplExprF body cont)
224 simplExprF expr@(Lam _ _) cont = simplLam expr cont
226 simplExprF (Type ty) cont
227 = ASSERT( case cont of { Stop _ _ -> True; ArgOf _ _ _ -> True; other -> False } )
228 simplType ty `thenSmpl` \ ty' ->
229 rebuild (Type ty') cont
231 -- Comments about the Coerce case
232 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
233 -- It's worth checking for a coerce in the continuation,
234 -- in case we can cancel them. For example, in the initial form of a worker
235 -- we may find (coerce T (coerce S (\x.e))) y
236 -- and we'd like it to simplify to e[y/x] in one round of simplification
238 simplExprF (Note (Coerce to from) e) (CoerceIt outer_to cont)
239 = simplType from `thenSmpl` \ from' ->
240 if outer_to == from' then
241 -- The coerces cancel out
244 -- They don't cancel, but the inner one is redundant
245 simplExprF e (CoerceIt outer_to cont)
247 simplExprF (Note (Coerce to from) e) cont
248 = simplType to `thenSmpl` \ to' ->
249 simplExprF e (CoerceIt to' cont)
251 -- hack: we only distinguish subsumed cost centre stacks for the purposes of
252 -- inlining. All other CCCSs are mapped to currentCCS.
253 simplExprF (Note (SCC cc) e) cont
254 = setEnclosingCC currentCCS $
255 simplExpr e `thenSmpl` \ e ->
256 rebuild (mkSCC cc e) cont
258 simplExprF (Note InlineCall e) cont
259 = simplExprF e (InlinePlease cont)
261 -- Comments about the InlineMe case
262 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
263 -- Don't inline in the RHS of something that has an
264 -- inline pragma. But be careful that the InScopeEnv that
265 -- we return does still have inlinings on!
267 -- It really is important to switch off inlinings. This function
268 -- may be inlinined in other modules, so we don't want to remove
269 -- (by inlining) calls to functions that have specialisations, or
270 -- that may have transformation rules in an importing scope.
271 -- E.g. {-# INLINE f #-}
273 -- and suppose that g is strict *and* has specialisations.
274 -- If we inline g's wrapper, we deny f the chance of getting
275 -- the specialised version of g when f is inlined at some call site
276 -- (perhaps in some other module).
278 -- It's also important not to inline a worker back into a wrapper.
279 -- A wrapper looks like
280 -- wraper = inline_me (\x -> ...worker... )
281 -- Normally, the inline_me prevents the worker getting inlined into
282 -- the wrapper (initially, the worker's only call site!). But,
283 -- if the wrapper is sure to be called, the strictness analyser will
284 -- mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf
285 -- continuation. That's why the keep_inline predicate returns True for
286 -- ArgOf continuations. It shouldn't do any harm not to dissolve the
287 -- inline-me note under these circumstances
289 simplExprF (Note InlineMe e) cont
290 | keep_inline cont -- Totally boring continuation
291 = -- Don't inline inside an INLINE expression
292 setBlackList noInlineBlackList (simplExpr e) `thenSmpl` \ e' ->
293 rebuild (mkInlineMe e') cont
295 | otherwise -- Dissolve the InlineMe note if there's
296 -- an interesting context of any kind to combine with
297 -- (even a type application -- anything except Stop)
300 keep_inline (Stop _ _) = True -- See notes above
301 keep_inline (ArgOf _ _ _) = True -- about this predicate
302 keep_inline other = False
304 -- A non-recursive let is dealt with by simplBeta
305 simplExprF (Let (NonRec bndr rhs) body) cont
306 = getSubstEnv `thenSmpl` \ se ->
307 simplBeta bndr rhs se (contResultType cont) $
312 ---------------------------------
318 zap_it = mkLamBndrZapper fun cont
319 cont_ty = contResultType cont
321 -- Type-beta reduction
322 go (Lam bndr body) (ApplyTo _ (Type ty_arg) arg_se body_cont)
323 = ASSERT( isTyVar bndr )
324 tick (BetaReduction bndr) `thenSmpl_`
325 simplTyArg ty_arg arg_se `thenSmpl` \ ty_arg' ->
326 extendSubst bndr (DoneTy ty_arg')
329 -- Ordinary beta reduction
330 go (Lam bndr body) cont@(ApplyTo _ arg arg_se body_cont)
331 = tick (BetaReduction bndr) `thenSmpl_`
332 simplBeta zapped_bndr arg arg_se cont_ty
335 zapped_bndr = zap_it bndr
338 go lam@(Lam _ _) cont = completeLam [] lam cont
340 -- Exactly enough args
341 go expr cont = simplExprF expr cont
343 -- completeLam deals with the case where a lambda doesn't have an ApplyTo
344 -- continuation, so there are real lambdas left to put in the result
346 -- We try for eta reduction here, but *only* if we get all the
347 -- way to an exprIsTrivial expression.
348 -- We don't want to remove extra lambdas unless we are going
349 -- to avoid allocating this thing altogether
351 completeLam rev_bndrs (Lam bndr body) cont
352 = simplBinder bndr $ \ bndr' ->
353 completeLam (bndr':rev_bndrs) body cont
355 completeLam rev_bndrs body cont
356 = simplExpr body `thenSmpl` \ body' ->
357 case try_eta body' of
358 Just etad_lam -> tick (EtaReduction (head rev_bndrs)) `thenSmpl_`
359 rebuild etad_lam cont
361 Nothing -> rebuild (foldl (flip Lam) body' rev_bndrs) cont
363 -- We don't use CoreUtils.etaReduce, because we can be more
364 -- efficient here: (a) we already have the binders, (b) we can do
365 -- the triviality test before computing the free vars
366 try_eta body | not opt_SimplDoEtaReduction = Nothing
367 | otherwise = go rev_bndrs body
369 go (b : bs) (App fun arg) | ok_arg b arg = go bs fun -- Loop round
370 go [] body | ok_body body = Just body -- Success!
371 go _ _ = Nothing -- Failure!
373 ok_body body = exprIsTrivial body && not (any (`elemVarSet` exprFreeVars body) rev_bndrs)
374 ok_arg b arg = varToCoreExpr b `cheapEqExpr` arg
376 mkLamBndrZapper :: CoreExpr -- Function
377 -> SimplCont -- The context
378 -> Id -> Id -- Use this to zap the binders
379 mkLamBndrZapper fun cont
380 | n_args >= n_params fun = \b -> b -- Enough args
381 | otherwise = \b -> zapLamIdInfo b
383 -- NB: we count all the args incl type args
384 -- so we must count all the binders (incl type lambdas)
385 n_args = countArgs cont
387 n_params (Note _ e) = n_params e
388 n_params (Lam b e) = 1 + n_params e
389 n_params other = 0::Int
393 ---------------------------------
395 simplType :: InType -> SimplM OutType
397 = getSubst `thenSmpl` \ subst ->
399 new_ty = substTy subst ty
406 %************************************************************************
410 %************************************************************************
412 @simplBeta@ is used for non-recursive lets in expressions,
413 as well as true beta reduction.
415 Very similar to @simplLazyBind@, but not quite the same.
418 simplBeta :: InId -- Binder
419 -> InExpr -> SubstEnv -- Arg, with its subst-env
420 -> OutType -- Type of thing computed by the context
421 -> SimplM OutExprStuff -- The body
422 -> SimplM OutExprStuff
424 simplBeta bndr rhs rhs_se cont_ty thing_inside
426 = pprPanic "simplBeta" (ppr bndr <+> ppr rhs)
429 simplBeta bndr rhs rhs_se cont_ty thing_inside
430 | preInlineUnconditionally False {- not black listed -} bndr
431 = tick (PreInlineUnconditionally bndr) `thenSmpl_`
432 extendSubst bndr (ContEx rhs_se rhs) thing_inside
435 = -- Simplify the RHS
436 simplBinder bndr $ \ bndr' ->
438 bndr_ty' = idType bndr'
439 is_strict = isStrict (idDemandInfo bndr) || isStrictType bndr_ty'
441 simplValArg bndr_ty' is_strict rhs rhs_se cont_ty $ \ rhs' ->
443 -- Now complete the binding and simplify the body
444 if needsCaseBinding bndr_ty' rhs' then
445 addCaseBind bndr' rhs' thing_inside
447 completeBinding bndr bndr' False False rhs' thing_inside
452 simplTyArg :: InType -> SubstEnv -> SimplM OutType
454 = getInScope `thenSmpl` \ in_scope ->
456 ty_arg' = substTy (mkSubst in_scope se) ty_arg
458 seqType ty_arg' `seq`
461 simplValArg :: OutType -- rhs_ty: Type of arg; used only occasionally
462 -> Bool -- True <=> evaluate eagerly
463 -> InExpr -> SubstEnv
464 -> OutType -- cont_ty: Type of thing computed by the context
465 -> (OutExpr -> SimplM OutExprStuff)
466 -- Takes an expression of type rhs_ty,
467 -- returns an expression of type cont_ty
468 -> SimplM OutExprStuff -- An expression of type cont_ty
470 simplValArg arg_ty is_strict arg arg_se cont_ty thing_inside
472 = getEnv `thenSmpl` \ env ->
474 simplExprF arg (ArgOf NoDup cont_ty $ \ rhs' ->
475 setAllExceptInScope env $
479 = simplRhs False {- Not top level -}
480 True {- OK to float unboxed -}
487 - deals only with Ids, not TyVars
488 - take an already-simplified RHS
490 It does *not* attempt to do let-to-case. Why? Because they are used for
493 (when let-to-case is impossible)
495 - many situations where the "rhs" is known to be a WHNF
496 (so let-to-case is inappropriate).
499 completeBinding :: InId -- Binder
500 -> OutId -- New binder
501 -> Bool -- True <=> top level
502 -> Bool -- True <=> black-listed; don't inline
503 -> OutExpr -- Simplified RHS
504 -> SimplM (OutStuff a) -- Thing inside
505 -> SimplM (OutStuff a)
507 completeBinding old_bndr new_bndr top_lvl black_listed new_rhs thing_inside
508 | isDeadOcc occ_info -- This happens; for example, the case_bndr during case of
509 -- known constructor: case (a,b) of x { (p,q) -> ... }
510 -- Here x isn't mentioned in the RHS, so we don't want to
511 -- create the (dead) let-binding let x = (a,b) in ...
514 | exprIsTrivial new_rhs
515 -- We're looking at a binding with a trivial RHS, so
516 -- perhaps we can discard it altogether!
518 -- NB: a loop breaker never has postInlineUnconditionally True
519 -- and non-loop-breakers only have *forward* references
520 -- Hence, it's safe to discard the binding
522 -- NOTE: This isn't our last opportunity to inline.
523 -- We're at the binding site right now, and
524 -- we'll get another opportunity when we get to the ocurrence(s)
526 -- Note that we do this unconditional inlining only for trival RHSs.
527 -- Don't inline even WHNFs inside lambdas; doing so may
528 -- simply increase allocation when the function is called
529 -- This isn't the last chance; see NOTE above.
531 -- NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here
532 -- Why? Because we don't even want to inline them into the
533 -- RHS of constructor arguments. See NOTE above
535 -- NB: Even NOINLINEis ignored here: if the rhs is trivial
536 -- it's best to inline it anyway. We often get a=E; b=a
537 -- from desugaring, with both a and b marked NOINLINE.
538 = if must_keep_binding then -- Keep the binding
539 finally_bind_it unknownArity new_rhs
540 -- Arity doesn't really matter because for a trivial RHS
541 -- we will inline like crazy at call sites
542 -- If this turns out be false, we can easily compute arity
543 else -- Drop the binding
544 extendSubst old_bndr (DoneEx new_rhs) $
545 -- Use the substitution to make quite, quite sure that the substitution
546 -- will happen, since we are going to discard the binding
547 tick (PostInlineUnconditionally old_bndr) `thenSmpl_`
550 | Note coercion@(Coerce _ inner_ty) inner_rhs <- new_rhs
551 -- [NB inner_rhs is guaranteed non-trivial by now]
552 -- x = coerce t e ==> c = e; x = inline_me (coerce t c)
553 -- Now x can get inlined, which moves the coercion
554 -- to the usage site. This is a bit like worker/wrapper stuff,
555 -- but it's useful to do it very promptly, so that
556 -- x = coerce T (I# 3)
560 -- This in turn means that
561 -- case (coerce Int x) of ...
563 -- Also the full-blown w/w thing isn't set up for non-functions
565 -- The inline_me note is so that the simplifier doesn't
566 -- just substitute c back inside x's rhs! (Typically, x will
567 -- get substituted away, but not if it's exported.)
568 = newId SLIT("c") inner_ty $ \ c_id ->
569 completeBinding c_id c_id top_lvl False inner_rhs $
570 completeBinding old_bndr new_bndr top_lvl black_listed
571 (Note InlineMe (Note coercion (Var c_id))) $
576 = transformRhs new_rhs finally_bind_it
579 old_info = idInfo old_bndr
580 occ_info = occInfo old_info
581 loop_breaker = isLoopBreaker occ_info
582 must_keep_binding = black_listed || loop_breaker || isExportedId old_bndr
584 finally_bind_it arity_info new_rhs
585 = getSubst `thenSmpl` \ subst ->
587 -- We make new IdInfo for the new binder by starting from the old binder,
588 -- doing appropriate substitutions.
589 -- Then we add arity and unfolding info to get the new binder
590 new_bndr_info = substIdInfo subst old_info (idInfo new_bndr)
591 `setArityInfo` arity_info
593 -- Add the unfolding *only* for non-loop-breakers
594 -- Making loop breakers not have an unfolding at all
595 -- means that we can avoid tests in exprIsConApp, for example.
596 -- This is important: if exprIsConApp says 'yes' for a recursive
597 -- thing, then we can get into an infinite loop
598 info_w_unf | loop_breaker = new_bndr_info
599 | otherwise = new_bndr_info `setUnfoldingInfo` mkUnfolding top_lvl new_rhs
601 final_id = new_bndr `setIdInfo` info_w_unf
603 -- These seqs forces the Id, and hence its IdInfo,
604 -- and hence any inner substitutions
606 addLetBind (NonRec final_id new_rhs) $
607 modifyInScope new_bndr final_id thing_inside
612 %************************************************************************
614 \subsection{simplLazyBind}
616 %************************************************************************
618 simplLazyBind basically just simplifies the RHS of a let(rec).
619 It does two important optimisations though:
621 * It floats let(rec)s out of the RHS, even if they
622 are hidden by big lambdas
624 * It does eta expansion
627 simplLazyBind :: Bool -- True <=> top level
630 -> SimplM (OutStuff a) -- The body of the binding
631 -> SimplM (OutStuff a)
632 -- When called, the subst env is correct for the entire let-binding
633 -- and hence right for the RHS.
634 -- Also the binder has already been simplified, and hence is in scope
636 simplLazyBind top_lvl bndr bndr' rhs thing_inside
637 = getBlackList `thenSmpl` \ black_list_fn ->
639 black_listed = black_list_fn bndr
642 if preInlineUnconditionally black_listed bndr then
643 -- Inline unconditionally
644 tick (PreInlineUnconditionally bndr) `thenSmpl_`
645 getSubstEnv `thenSmpl` \ rhs_se ->
646 (extendSubst bndr (ContEx rhs_se rhs) thing_inside)
650 getSubstEnv `thenSmpl` \ rhs_se ->
651 simplRhs top_lvl False {- Not ok to float unboxed (conservative) -}
653 rhs rhs_se $ \ rhs' ->
655 -- Now compete the binding and simplify the body
656 completeBinding bndr bndr' top_lvl black_listed rhs' thing_inside
662 simplRhs :: Bool -- True <=> Top level
663 -> Bool -- True <=> OK to float unboxed (speculative) bindings
664 -- False for (a) recursive and (b) top-level bindings
665 -> OutType -- Type of RHS; used only occasionally
666 -> InExpr -> SubstEnv
667 -> (OutExpr -> SimplM (OutStuff a))
668 -> SimplM (OutStuff a)
669 simplRhs top_lvl float_ubx rhs_ty rhs rhs_se thing_inside
671 setSubstEnv rhs_se (simplExprF rhs (mkRhsStop rhs_ty)) `thenSmpl` \ (floats, (in_scope', rhs')) ->
673 -- Float lets out of RHS
675 (floats_out, rhs'') = splitFloats float_ubx floats rhs'
677 if (top_lvl || wantToExpose 0 rhs') && -- Float lets if (a) we're at the top level
678 not (null floats_out) -- or (b) the resulting RHS is one we'd like to expose
680 tickLetFloat floats_out `thenSmpl_`
683 -- There's a subtlety here. There may be a binding (x* = e) in the
684 -- floats, where the '*' means 'will be demanded'. So is it safe
685 -- to float it out? Answer no, but it won't matter because
686 -- we only float if arg' is a WHNF,
687 -- and so there can't be any 'will be demanded' bindings in the floats.
689 WARN( any demanded_float floats_out, ppr floats_out )
690 addLetBinds floats_out $
691 setInScope in_scope' $
693 -- in_scope' may be excessive, but that's OK;
694 -- it's a superset of what's in scope
696 -- Don't do the float
697 thing_inside (mkLets floats rhs')
699 -- In a let-from-let float, we just tick once, arbitrarily
700 -- choosing the first floated binder to identify it
701 tickLetFloat (NonRec b r : fs) = tick (LetFloatFromLet b)
702 tickLetFloat (Rec ((b,r):prs) : fs) = tick (LetFloatFromLet b)
704 demanded_float (NonRec b r) = isStrict (idDemandInfo b) && not (isUnLiftedType (idType b))
705 -- Unlifted-type (cheap-eagerness) lets may well have a demanded flag on them
706 demanded_float (Rec _) = False
708 -- If float_ubx is true we float all the bindings, otherwise
709 -- we just float until we come across an unlifted one.
710 -- Remember that the unlifted bindings in the floats are all for
711 -- guaranteed-terminating non-exception-raising unlifted things,
712 -- which we are happy to do speculatively. However, we may still
713 -- not be able to float them out, because the context
714 -- is either a Rec group, or the top level, neither of which
715 -- can tolerate them.
716 splitFloats float_ubx floats rhs
717 | float_ubx = (floats, rhs) -- Float them all
718 | otherwise = go floats
721 go (f:fs) | must_stay f = ([], mkLets (f:fs) rhs)
722 | otherwise = case go fs of
723 (out, rhs') -> (f:out, rhs')
725 must_stay (Rec prs) = False -- No unlifted bindings in here
726 must_stay (NonRec b r) = isUnLiftedType (idType b)
728 wantToExpose :: Int -> CoreExpr -> Bool
729 -- True for expressions that we'd like to expose at the
730 -- top level of an RHS. This includes partial applications
731 -- even if the args aren't cheap; the next pass will let-bind the
732 -- args and eta expand the partial application. So exprIsCheap won't do.
733 -- Here's the motivating example:
734 -- z = letrec g = \x y -> ...g... in g E
735 -- Even though E is a redex we'd like to float the letrec to give
736 -- g = \x y -> ...g...
738 -- Now the next use of SimplUtils.tryEtaExpansion will give
739 -- g = \x y -> ...g...
740 -- z = let v = E in \w -> g v w
741 -- And now we'll float the v to give
742 -- g = \x y -> ...g...
745 -- Which is what we want; chances are z will be inlined now.
747 wantToExpose n (Var v) = idAppIsCheap v n
748 wantToExpose n (Lit l) = True
749 wantToExpose n (Lam _ e) = True
750 wantToExpose n (Note _ e) = wantToExpose n e
751 wantToExpose n (App f (Type _)) = wantToExpose n f
752 wantToExpose n (App f a) = wantToExpose (n+1) f
753 wantToExpose n other = False -- There won't be any lets
758 %************************************************************************
760 \subsection{Variables}
762 %************************************************************************
766 = getSubst `thenSmpl` \ subst ->
767 case lookupIdSubst subst var of
768 DoneEx e -> zapSubstEnv (simplExprF e cont)
769 ContEx env1 e -> setSubstEnv env1 (simplExprF e cont)
770 DoneId var1 occ -> WARN( not (isInScope var1 subst) && mustHaveLocalBinding var1,
771 text "simplVar:" <+> ppr var )
772 zapSubstEnv (completeCall var1 occ cont)
773 -- The template is already simplified, so don't re-substitute.
774 -- This is VITAL. Consider
776 -- let y = \z -> ...x... in
778 -- We'll clone the inner \x, adding x->x' in the id_subst
779 -- Then when we inline y, we must *not* replace x by x' in
780 -- the inlined copy!!
782 ---------------------------------------------------------
783 -- Dealing with a call
785 completeCall var occ cont
786 = getBlackList `thenSmpl` \ black_list_fn ->
787 getInScope `thenSmpl` \ in_scope ->
788 getContArgs var cont `thenSmpl` \ (args, call_cont, inline_call) ->
789 getDOptsSmpl `thenSmpl` \ dflags ->
791 black_listed = black_list_fn var
792 arg_infos = [ interestingArg in_scope arg subst
793 | (arg, subst, _) <- args, isValArg arg]
795 interesting_cont = interestingCallContext (not (null args))
796 (not (null arg_infos))
799 inline_cont | inline_call = discardInline cont
802 maybe_inline = callSiteInline dflags black_listed inline_call occ
803 var arg_infos interesting_cont
805 -- First, look for an inlining
806 case maybe_inline of {
807 Just unfolding -- There is an inlining!
808 -> tick (UnfoldingDone var) `thenSmpl_`
809 simplExprF unfolding inline_cont
812 Nothing -> -- No inlining!
815 simplifyArgs (isDataConId var) args (contResultType call_cont) $ \ args' ->
817 -- Next, look for rules or specialisations that match
819 -- It's important to simplify the args first, because the rule-matcher
820 -- doesn't do substitution as it goes. We don't want to use subst_args
821 -- (defined in the 'where') because that throws away useful occurrence info,
822 -- and perhaps-very-important specialisations.
824 -- Some functions have specialisations *and* are strict; in this case,
825 -- we don't want to inline the wrapper of the non-specialised thing; better
826 -- to call the specialised thing instead.
827 -- But the black-listing mechanism means that inlining of the wrapper
828 -- won't occur for things that have specialisations till a later phase, so
829 -- it's ok to try for inlining first.
831 getSwitchChecker `thenSmpl` \ chkr ->
833 maybe_rule | switchIsOn chkr DontApplyRules = Nothing
834 | otherwise = lookupRule in_scope var args'
837 Just (rule_name, rule_rhs) ->
838 tick (RuleFired rule_name) `thenSmpl_`
839 simplExprF rule_rhs call_cont ;
841 Nothing -> -- No rules
844 rebuild (mkApps (Var var) args') call_cont
848 ---------------------------------------------------------
849 -- Simplifying the arguments of a call
851 simplifyArgs :: Bool -- It's a data constructor
852 -> [(InExpr, SubstEnv, Bool)] -- Details of the arguments
853 -> OutType -- Type of the continuation
854 -> ([OutExpr] -> SimplM OutExprStuff)
855 -> SimplM OutExprStuff
857 -- Simplify the arguments to a call.
858 -- This part of the simplifier may break the no-shadowing invariant
860 -- f (...(\a -> e)...) (case y of (a,b) -> e')
861 -- where f is strict in its second arg
862 -- If we simplify the innermost one first we get (...(\a -> e)...)
863 -- Simplifying the second arg makes us float the case out, so we end up with
864 -- case y of (a,b) -> f (...(\a -> e)...) e'
865 -- So the output does not have the no-shadowing invariant. However, there is
866 -- no danger of getting name-capture, because when the first arg was simplified
867 -- we used an in-scope set that at least mentioned all the variables free in its
868 -- static environment, and that is enough.
870 -- We can't just do innermost first, or we'd end up with a dual problem:
871 -- case x of (a,b) -> f e (...(\a -> e')...)
873 -- I spent hours trying to recover the no-shadowing invariant, but I just could
874 -- not think of an elegant way to do it. The simplifier is already knee-deep in
875 -- continuations. We have to keep the right in-scope set around; AND we have
876 -- to get the effect that finding (error "foo") in a strict arg position will
877 -- discard the entire application and replace it with (error "foo"). Getting
878 -- all this at once is TOO HARD!
880 simplifyArgs is_data_con args cont_ty thing_inside
882 = go args thing_inside
884 | otherwise -- It's a data constructor, so we want
885 -- to switch off inlining in the arguments
886 -- If we don't do this, consider:
887 -- let x = +# p q in C {x}
888 -- Even though x get's an occurrence of 'many', its RHS looks cheap,
889 -- and there's a good chance it'll get inlined back into C's RHS. Urgh!
890 = getBlackList `thenSmpl` \ old_bl ->
891 setBlackList noInlineBlackList $
893 setBlackList old_bl $
897 go [] thing_inside = thing_inside []
898 go (arg:args) thing_inside = simplifyArg is_data_con arg cont_ty $ \ arg' ->
900 thing_inside (arg':args')
902 simplifyArg is_data_con (Type ty_arg, se, _) cont_ty thing_inside
903 = simplTyArg ty_arg se `thenSmpl` \ new_ty_arg ->
904 thing_inside (Type new_ty_arg)
906 simplifyArg is_data_con (val_arg, se, is_strict) cont_ty thing_inside
907 = getInScope `thenSmpl` \ in_scope ->
909 arg_ty = substTy (mkSubst in_scope se) (exprType val_arg)
911 if not is_data_con then
912 -- An ordinary function
913 simplValArg arg_ty is_strict val_arg se cont_ty thing_inside
915 -- A data constructor
916 -- simplifyArgs has already switched off inlining, so
917 -- all we have to do here is to let-bind any non-trivial argument
919 -- It's not always the case that new_arg will be trivial
921 -- where, in one pass, f gets substituted by a constructor,
922 -- but x gets substituted by an expression (assume this is the
923 -- unique occurrence of x). It doesn't really matter -- it'll get
924 -- fixed up next pass. And it happens for dictionary construction,
925 -- which mentions the wrapper constructor to start with.
926 simplValArg arg_ty is_strict val_arg se cont_ty $ \ arg' ->
928 if exprIsTrivial arg' then
931 newId SLIT("a") (exprType arg') $ \ arg_id ->
932 addNonRecBind arg_id arg' $
933 thing_inside (Var arg_id)
937 %************************************************************************
939 \subsection{Decisions about inlining}
941 %************************************************************************
943 NB: At one time I tried not pre/post-inlining top-level things,
944 even if they occur exactly once. Reason:
945 (a) some might appear as a function argument, so we simply
946 replace static allocation with dynamic allocation:
952 (b) some top level things might be black listed
954 HOWEVER, I found that some useful foldr/build fusion was lost (most
955 notably in spectral/hartel/parstof) because the foldr didn't see the build.
957 Doing the dynamic allocation isn't a big deal, in fact, but losing the
961 preInlineUnconditionally :: Bool {- Black listed -} -> InId -> Bool
962 -- Examines a bndr to see if it is used just once in a
963 -- completely safe way, so that it is safe to discard the binding
964 -- inline its RHS at the (unique) usage site, REGARDLESS of how
965 -- big the RHS might be. If this is the case we don't simplify
966 -- the RHS first, but just inline it un-simplified.
968 -- This is much better than first simplifying a perhaps-huge RHS
969 -- and then inlining and re-simplifying it.
971 -- NB: we don't even look at the RHS to see if it's trivial
974 -- where x is used many times, but this is the unique occurrence
975 -- of y. We should NOT inline x at all its uses, because then
976 -- we'd do the same for y -- aargh! So we must base this
977 -- pre-rhs-simplification decision solely on x's occurrences, not
980 -- Evne RHSs labelled InlineMe aren't caught here, because
981 -- there might be no benefit from inlining at the call site.
983 preInlineUnconditionally black_listed bndr
984 | black_listed || opt_SimplNoPreInlining = False
985 | otherwise = case idOccInfo bndr of
986 OneOcc in_lam once -> not in_lam && once
987 -- Not inside a lambda, one occurrence ==> safe!
993 %************************************************************************
995 \subsection{The main rebuilder}
997 %************************************************************************
1000 -------------------------------------------------------------------
1001 -- Finish rebuilding
1003 = getInScope `thenSmpl` \ in_scope ->
1004 returnSmpl ([], (in_scope, expr))
1006 ---------------------------------------------------------
1007 rebuild :: OutExpr -> SimplCont -> SimplM OutExprStuff
1009 -- Stop continuation
1010 rebuild expr (Stop _ _) = rebuild_done expr
1012 -- ArgOf continuation
1013 rebuild expr (ArgOf _ _ cont_fn) = cont_fn expr
1015 -- ApplyTo continuation
1016 rebuild expr cont@(ApplyTo _ arg se cont')
1017 = setSubstEnv se (simplExpr arg) `thenSmpl` \ arg' ->
1018 rebuild (App expr arg') cont'
1020 -- Coerce continuation
1021 rebuild expr (CoerceIt to_ty cont)
1022 = rebuild (mkCoerce to_ty (exprType expr) expr) cont
1024 -- Inline continuation
1025 rebuild expr (InlinePlease cont)
1026 = rebuild (Note InlineCall expr) cont
1028 rebuild scrut (Select _ bndr alts se cont)
1029 = rebuild_case scrut bndr alts se cont
1032 Case elimination [see the code above]
1034 Start with a simple situation:
1036 case x# of ===> e[x#/y#]
1039 (when x#, y# are of primitive type, of course). We can't (in general)
1040 do this for algebraic cases, because we might turn bottom into
1043 Actually, we generalise this idea to look for a case where we're
1044 scrutinising a variable, and we know that only the default case can
1049 other -> ...(case x of
1053 Here the inner case can be eliminated. This really only shows up in
1054 eliminating error-checking code.
1056 We also make sure that we deal with this very common case:
1061 Here we are using the case as a strict let; if x is used only once
1062 then we want to inline it. We have to be careful that this doesn't
1063 make the program terminate when it would have diverged before, so we
1065 - x is used strictly, or
1066 - e is already evaluated (it may so if e is a variable)
1068 Lastly, we generalise the transformation to handle this:
1074 We only do this for very cheaply compared r's (constructors, literals
1075 and variables). If pedantic bottoms is on, we only do it when the
1076 scrutinee is a PrimOp which can't fail.
1078 We do it *here*, looking at un-simplified alternatives, because we
1079 have to check that r doesn't mention the variables bound by the
1080 pattern in each alternative, so the binder-info is rather useful.
1082 So the case-elimination algorithm is:
1084 1. Eliminate alternatives which can't match
1086 2. Check whether all the remaining alternatives
1087 (a) do not mention in their rhs any of the variables bound in their pattern
1088 and (b) have equal rhss
1090 3. Check we can safely ditch the case:
1091 * PedanticBottoms is off,
1092 or * the scrutinee is an already-evaluated variable
1093 or * the scrutinee is a primop which is ok for speculation
1094 -- ie we want to preserve divide-by-zero errors, and
1095 -- calls to error itself!
1097 or * [Prim cases] the scrutinee is a primitive variable
1099 or * [Alg cases] the scrutinee is a variable and
1100 either * the rhs is the same variable
1101 (eg case x of C a b -> x ===> x)
1102 or * there is only one alternative, the default alternative,
1103 and the binder is used strictly in its scope.
1104 [NB this is helped by the "use default binder where
1105 possible" transformation; see below.]
1108 If so, then we can replace the case with one of the rhss.
1111 Blob of helper functions for the "case-of-something-else" situation.
1114 ---------------------------------------------------------
1115 -- Eliminate the case if possible
1117 rebuild_case scrut bndr alts se cont
1118 | maybeToBool maybe_con_app
1119 = knownCon scrut (DataAlt con) args bndr alts se cont
1121 | canEliminateCase scrut bndr alts
1122 = tick (CaseElim bndr) `thenSmpl_` (
1124 simplBinder bndr $ \ bndr' ->
1125 -- Remember to bind the case binder!
1126 completeBinding bndr bndr' False False scrut $
1127 simplExprF (head (rhssOfAlts alts)) cont)
1130 = complete_case scrut bndr alts se cont
1133 maybe_con_app = exprIsConApp_maybe scrut
1134 Just (con, args) = maybe_con_app
1136 -- See if we can get rid of the case altogether
1137 -- See the extensive notes on case-elimination above
1138 canEliminateCase scrut bndr alts
1139 = -- Check that the RHSs are all the same, and
1140 -- don't use the binders in the alternatives
1141 -- This test succeeds rapidly in the common case of
1142 -- a single DEFAULT alternative
1143 all (cheapEqExpr rhs1) other_rhss && all binders_unused alts
1145 -- Check that the scrutinee can be let-bound instead of case-bound
1146 && ( exprOkForSpeculation scrut
1147 -- OK not to evaluate it
1148 -- This includes things like (==# a# b#)::Bool
1149 -- so that we simplify
1150 -- case ==# a# b# of { True -> x; False -> x }
1153 -- This particular example shows up in default methods for
1154 -- comparision operations (e.g. in (>=) for Int.Int32)
1155 || exprIsValue scrut -- It's already evaluated
1156 || var_demanded_later scrut -- It'll be demanded later
1158 -- || not opt_SimplPedanticBottoms) -- Or we don't care!
1159 -- We used to allow improving termination by discarding cases, unless -fpedantic-bottoms was on,
1160 -- but that breaks badly for the dataToTag# primop, which relies on a case to evaluate
1161 -- its argument: case x of { y -> dataToTag# y }
1162 -- Here we must *not* discard the case, because dataToTag# just fetches the tag from
1163 -- the info pointer. So we'll be pedantic all the time, and see if that gives any
1168 (rhs1:other_rhss) = rhssOfAlts alts
1169 binders_unused (_, bndrs, _) = all isDeadBinder bndrs
1171 var_demanded_later (Var v) = isStrict (idDemandInfo bndr) -- It's going to be evaluated later
1172 var_demanded_later other = False
1175 ---------------------------------------------------------
1176 -- Case of something else
1178 complete_case scrut case_bndr alts se cont
1179 = -- Prepare case alternatives
1180 prepareCaseAlts case_bndr (splitTyConApp_maybe (idType case_bndr))
1181 impossible_cons alts `thenSmpl` \ better_alts ->
1183 -- Set the new subst-env in place (before dealing with the case binder)
1186 -- Deal with the case binder, and prepare the continuation;
1187 -- The new subst_env is in place
1188 prepareCaseCont better_alts cont $ \ cont' ->
1191 -- Deal with variable scrutinee
1193 getSwitchChecker `thenSmpl` \ chkr ->
1194 simplCaseBinder (switchIsOn chkr NoCaseOfCase)
1195 scrut case_bndr $ \ case_bndr' zap_occ_info ->
1197 -- Deal with the case alternatives
1198 simplAlts zap_occ_info impossible_cons
1199 case_bndr' better_alts cont' `thenSmpl` \ alts' ->
1201 mkCase scrut case_bndr' alts'
1202 ) `thenSmpl` \ case_expr ->
1204 -- Notice that the simplBinder, prepareCaseCont, etc, do *not* scope
1205 -- over the rebuild_done; rebuild_done returns the in-scope set, and
1206 -- that should not include these chaps!
1207 rebuild_done case_expr
1209 impossible_cons = case scrut of
1210 Var v -> otherCons (idUnfolding v)
1214 knownCon :: OutExpr -> AltCon -> [OutExpr]
1215 -> InId -> [InAlt] -> SubstEnv -> SimplCont
1216 -> SimplM OutExprStuff
1218 knownCon expr con args bndr alts se cont
1219 = tick (KnownBranch bndr) `thenSmpl_`
1221 simplBinder bndr $ \ bndr' ->
1222 completeBinding bndr bndr' False False expr $
1223 -- Don't use completeBeta here. The expr might be
1224 -- an unboxed literal, like 3, or a variable
1225 -- whose unfolding is an unboxed literal... and
1226 -- completeBeta will just construct another case
1228 case findAlt con alts of
1229 (DEFAULT, bs, rhs) -> ASSERT( null bs )
1232 (LitAlt lit, bs, rhs) -> ASSERT( null bs )
1235 (DataAlt dc, bs, rhs) -> ASSERT( length bs == length real_args )
1236 extendSubstList bs (map mk real_args) $
1239 real_args = drop (dataConNumInstArgs dc) args
1240 mk (Type ty) = DoneTy ty
1241 mk other = DoneEx other
1246 prepareCaseCont :: [InAlt] -> SimplCont
1247 -> (SimplCont -> SimplM (OutStuff a))
1248 -> SimplM (OutStuff a)
1249 -- Polymorphic recursion here!
1251 prepareCaseCont [alt] cont thing_inside = thing_inside cont
1252 prepareCaseCont alts cont thing_inside = simplType (coreAltsType alts) `thenSmpl` \ alts_ty ->
1253 mkDupableCont alts_ty cont thing_inside
1254 -- At one time I passed in the un-simplified type, and simplified
1255 -- it only if we needed to construct a join binder, but that
1256 -- didn't work because we have to decompse function types
1257 -- (using funResultTy) in mkDupableCont.
1260 simplCaseBinder checks whether the scrutinee is a variable, v. If so,
1261 try to eliminate uses of v in the RHSs in favour of case_bndr; that
1262 way, there's a chance that v will now only be used once, and hence
1265 There is a time we *don't* want to do that, namely when
1266 -fno-case-of-case is on. This happens in the first simplifier pass,
1267 and enhances full laziness. Here's the bad case:
1268 f = \ y -> ...(case x of I# v -> ...(case x of ...) ... )
1269 If we eliminate the inner case, we trap it inside the I# v -> arm,
1270 which might prevent some full laziness happening. I've seen this
1271 in action in spectral/cichelli/Prog.hs:
1272 [(m,n) | m <- [1..max], n <- [1..max]]
1273 Hence the no_case_of_case argument
1276 If we do this, then we have to nuke any occurrence info (eg IAmDead)
1277 in the case binder, because the case-binder now effectively occurs
1278 whenever v does. AND we have to do the same for the pattern-bound
1281 (case x of { (a,b) -> a }) (case x of { (p,q) -> q })
1283 Here, b and p are dead. But when we move the argment inside the first
1284 case RHS, and eliminate the second case, we get
1286 case x or { (a,b) -> a b }
1288 Urk! b is alive! Reason: the scrutinee was a variable, and case elimination
1289 happened. Hence the zap_occ_info function returned by simplCaseBinder
1292 simplCaseBinder no_case_of_case (Var v) case_bndr thing_inside
1293 | not no_case_of_case
1294 = simplBinder (zap case_bndr) $ \ case_bndr' ->
1295 modifyInScope v case_bndr' $
1296 -- We could extend the substitution instead, but it would be
1297 -- a hack because then the substitution wouldn't be idempotent
1298 -- any more (v is an OutId). And this just just as well.
1299 thing_inside case_bndr' zap
1301 zap b = b `setIdOccInfo` NoOccInfo
1303 simplCaseBinder add_eval_info other_scrut case_bndr thing_inside
1304 = simplBinder case_bndr $ \ case_bndr' ->
1305 thing_inside case_bndr' (\ bndr -> bndr) -- NoOp on bndr
1308 prepareCaseAlts does two things:
1310 1. Remove impossible alternatives
1312 2. If the DEFAULT alternative can match only one possible constructor,
1313 then make that constructor explicit.
1315 case e of x { DEFAULT -> rhs }
1317 case e of x { (a,b) -> rhs }
1318 where the type is a single constructor type. This gives better code
1319 when rhs also scrutinises x or e.
1322 prepareCaseAlts bndr (Just (tycon, inst_tys)) scrut_cons alts
1324 = case (findDefault filtered_alts, missing_cons) of
1326 ((alts_no_deflt, Just rhs), [data_con]) -- Just one missing constructor!
1327 -> tick (FillInCaseDefault bndr) `thenSmpl_`
1329 (_,_,ex_tyvars,_,_,_) = dataConSig data_con
1331 getUniquesSmpl (length ex_tyvars) `thenSmpl` \ tv_uniqs ->
1333 ex_tyvars' = zipWithEqual "simpl_alt" mk tv_uniqs ex_tyvars
1334 mk uniq tv = mkSysTyVar uniq (tyVarKind tv)
1335 arg_tys = dataConArgTys data_con
1336 (inst_tys ++ mkTyVarTys ex_tyvars')
1338 newIds SLIT("a") arg_tys $ \ bndrs ->
1339 returnSmpl ((DataAlt data_con, ex_tyvars' ++ bndrs, rhs) : alts_no_deflt)
1341 other -> returnSmpl filtered_alts
1343 -- Filter out alternatives that can't possibly match
1344 filtered_alts = case scrut_cons of
1346 other -> [alt | alt@(con,_,_) <- alts, not (con `elem` scrut_cons)]
1348 missing_cons = [data_con | data_con <- tyConDataConsIfAvailable tycon,
1349 not (data_con `elem` handled_data_cons)]
1350 handled_data_cons = [data_con | DataAlt data_con <- scrut_cons] ++
1351 [data_con | (DataAlt data_con, _, _) <- filtered_alts]
1354 prepareCaseAlts _ _ scrut_cons alts
1355 = returnSmpl alts -- Functions
1358 ----------------------
1359 simplAlts zap_occ_info scrut_cons case_bndr' alts cont'
1360 = mapSmpl simpl_alt alts
1362 inst_tys' = tyConAppArgs (idType case_bndr')
1364 -- handled_cons is all the constructors that are dealt
1365 -- with, either by being impossible, or by there being an alternative
1366 handled_cons = scrut_cons ++ [con | (con,_,_) <- alts, con /= DEFAULT]
1368 simpl_alt (DEFAULT, _, rhs)
1369 = -- In the default case we record the constructors that the
1370 -- case-binder *can't* be.
1371 -- We take advantage of any OtherCon info in the case scrutinee
1372 modifyInScope case_bndr' (case_bndr' `setIdUnfolding` mkOtherCon handled_cons) $
1373 simplExprC rhs cont' `thenSmpl` \ rhs' ->
1374 returnSmpl (DEFAULT, [], rhs')
1376 simpl_alt (con, vs, rhs)
1377 = -- Deal with the pattern-bound variables
1378 -- Mark the ones that are in ! positions in the data constructor
1379 -- as certainly-evaluated.
1380 -- NB: it happens that simplBinders does *not* erase the OtherCon
1381 -- form of unfolding, so it's ok to add this info before
1382 -- doing simplBinders
1383 simplBinders (add_evals con vs) $ \ vs' ->
1385 -- Bind the case-binder to (con args)
1387 unfolding = mkUnfolding False (mkAltExpr con vs' inst_tys')
1389 modifyInScope case_bndr' (case_bndr' `setIdUnfolding` unfolding) $
1390 simplExprC rhs cont' `thenSmpl` \ rhs' ->
1391 returnSmpl (con, vs', rhs')
1394 -- add_evals records the evaluated-ness of the bound variables of
1395 -- a case pattern. This is *important*. Consider
1396 -- data T = T !Int !Int
1398 -- case x of { T a b -> T (a+1) b }
1400 -- We really must record that b is already evaluated so that we don't
1401 -- go and re-evaluate it when constructing the result.
1403 add_evals (DataAlt dc) vs = cat_evals vs (dataConRepStrictness dc)
1404 add_evals other_con vs = vs
1406 cat_evals [] [] = []
1407 cat_evals (v:vs) (str:strs)
1408 | isTyVar v = v : cat_evals vs (str:strs)
1409 | isStrict str = (v' `setIdUnfolding` mkOtherCon []) : cat_evals vs strs
1410 | otherwise = v' : cat_evals vs strs
1416 %************************************************************************
1418 \subsection{Duplicating continuations}
1420 %************************************************************************
1423 mkDupableCont :: OutType -- Type of the thing to be given to the continuation
1425 -> (SimplCont -> SimplM (OutStuff a))
1426 -> SimplM (OutStuff a)
1427 mkDupableCont ty cont thing_inside
1428 | contIsDupable cont
1431 mkDupableCont _ (CoerceIt ty cont) thing_inside
1432 = mkDupableCont ty cont $ \ cont' ->
1433 thing_inside (CoerceIt ty cont')
1435 mkDupableCont ty (InlinePlease cont) thing_inside
1436 = mkDupableCont ty cont $ \ cont' ->
1437 thing_inside (InlinePlease cont')
1439 mkDupableCont join_arg_ty (ArgOf _ cont_ty cont_fn) thing_inside
1440 = -- Build the RHS of the join point
1441 newId SLIT("a") join_arg_ty ( \ arg_id ->
1442 cont_fn (Var arg_id) `thenSmpl` \ (binds, (_, rhs)) ->
1443 returnSmpl (Lam (setOneShotLambda arg_id) (mkLets binds rhs))
1444 ) `thenSmpl` \ join_rhs ->
1446 -- Build the join Id and continuation
1447 -- We give it a "$j" name just so that for later amusement
1448 -- we can identify any join points that don't end up as let-no-escapes
1449 -- [NOTE: the type used to be exprType join_rhs, but this seems more elegant.]
1450 newId SLIT("$j") (mkFunTy join_arg_ty cont_ty) $ \ join_id ->
1452 new_cont = ArgOf OkToDup cont_ty
1453 (\arg' -> rebuild_done (App (Var join_id) arg'))
1456 tick (CaseOfCase join_id) `thenSmpl_`
1457 -- Want to tick here so that we go round again,
1458 -- and maybe copy or inline the code;
1459 -- not strictly CaseOf Case
1460 addLetBind (NonRec join_id join_rhs) $
1461 thing_inside new_cont
1463 mkDupableCont ty (ApplyTo _ arg se cont) thing_inside
1464 = mkDupableCont (funResultTy ty) cont $ \ cont' ->
1465 setSubstEnv se (simplExpr arg) `thenSmpl` \ arg' ->
1466 if exprIsDupable arg' then
1467 thing_inside (ApplyTo OkToDup arg' emptySubstEnv cont')
1469 newId SLIT("a") (exprType arg') $ \ bndr ->
1471 tick (CaseOfCase bndr) `thenSmpl_`
1472 -- Want to tick here so that we go round again,
1473 -- and maybe copy or inline the code;
1474 -- not strictly CaseOf Case
1476 addLetBind (NonRec bndr arg') $
1477 -- But what if the arg should be case-bound? We can't use
1478 -- addNonRecBind here because its type is too specific.
1479 -- This has been this way for a long time, so I'll leave it,
1480 -- but I can't convince myself that it's right.
1482 thing_inside (ApplyTo OkToDup (Var bndr) emptySubstEnv cont')
1485 mkDupableCont ty (Select _ case_bndr alts se cont) thing_inside
1486 = tick (CaseOfCase case_bndr) `thenSmpl_`
1488 simplBinder case_bndr $ \ case_bndr' ->
1489 prepareCaseCont alts cont $ \ cont' ->
1490 mapAndUnzipSmpl (mkDupableAlt case_bndr case_bndr' cont') alts `thenSmpl` \ (alt_binds_s, alts') ->
1491 returnSmpl (concat alt_binds_s, alts')
1492 ) `thenSmpl` \ (alt_binds, alts') ->
1494 addAuxiliaryBinds alt_binds $
1496 -- NB that the new alternatives, alts', are still InAlts, using the original
1497 -- binders. That means we can keep the case_bndr intact. This is important
1498 -- because another case-of-case might strike, and so we want to keep the
1499 -- info that the case_bndr is dead (if it is, which is often the case).
1500 -- This is VITAL when the type of case_bndr is an unboxed pair (often the
1501 -- case in I/O rich code. We aren't allowed a lambda bound
1502 -- arg of unboxed tuple type, and indeed such a case_bndr is always dead
1503 thing_inside (Select OkToDup case_bndr alts' se (mkStop (contResultType cont)))
1505 mkDupableAlt :: InId -> OutId -> SimplCont -> InAlt -> SimplM (OutStuff InAlt)
1506 mkDupableAlt case_bndr case_bndr' cont alt@(con, bndrs, rhs)
1507 = simplBinders bndrs $ \ bndrs' ->
1508 simplExprC rhs cont `thenSmpl` \ rhs' ->
1510 if (case cont of { Stop _ _ -> exprIsDupable rhs'; other -> False}) then
1511 -- It is worth checking for a small RHS because otherwise we
1512 -- get extra let bindings that may cause an extra iteration of the simplifier to
1513 -- inline back in place. Quite often the rhs is just a variable or constructor.
1514 -- The Ord instance of Maybe in PrelMaybe.lhs, for example, took several extra
1515 -- iterations because the version with the let bindings looked big, and so wasn't
1516 -- inlined, but after the join points had been inlined it looked smaller, and so
1519 -- But since the continuation is absorbed into the rhs, we only do this
1520 -- for a Stop continuation.
1522 -- NB: we have to check the size of rhs', not rhs.
1523 -- Duplicating a small InAlt might invalidate occurrence information
1524 -- However, if it *is* dupable, we return the *un* simplified alternative,
1525 -- because otherwise we'd need to pair it up with an empty subst-env.
1526 -- (Remember we must zap the subst-env before re-simplifying something).
1527 -- Rather than do this we simply agree to re-simplify the original (small) thing later.
1528 returnSmpl ([], alt)
1532 rhs_ty' = exprType rhs'
1533 (used_bndrs, used_bndrs')
1534 = unzip [pr | pr@(bndr,bndr') <- zip (case_bndr : bndrs)
1535 (case_bndr' : bndrs'),
1536 not (isDeadBinder bndr)]
1537 -- The new binders have lost their occurrence info,
1538 -- so we have to extract it from the old ones
1540 ( if null used_bndrs'
1541 -- If we try to lift a primitive-typed something out
1542 -- for let-binding-purposes, we will *caseify* it (!),
1543 -- with potentially-disastrous strictness results. So
1544 -- instead we turn it into a function: \v -> e
1545 -- where v::State# RealWorld#. The value passed to this function
1546 -- is realworld#, which generates (almost) no code.
1548 -- There's a slight infelicity here: we pass the overall
1549 -- case_bndr to all the join points if it's used in *any* RHS,
1550 -- because we don't know its usage in each RHS separately
1552 -- We used to say "&& isUnLiftedType rhs_ty'" here, but now
1553 -- we make the join point into a function whenever used_bndrs'
1554 -- is empty. This makes the join-point more CPR friendly.
1555 -- Consider: let j = if .. then I# 3 else I# 4
1556 -- in case .. of { A -> j; B -> j; C -> ... }
1558 -- Now CPR should not w/w j because it's a thunk, so
1559 -- that means that the enclosing function can't w/w either,
1560 -- which is a lose. Here's the example that happened in practice:
1561 -- kgmod :: Int -> Int -> Int
1562 -- kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
1566 then newId SLIT("w") realWorldStatePrimTy $ \ rw_id ->
1567 returnSmpl ([rw_id], [Var realWorldPrimId])
1569 returnSmpl (used_bndrs', map varToCoreExpr used_bndrs)
1571 `thenSmpl` \ (final_bndrs', final_args) ->
1573 -- See comment about "$j" name above
1574 newId SLIT("$j") (foldr mkPiType rhs_ty' final_bndrs') $ \ join_bndr ->
1575 -- Notice the funky mkPiType. If the contructor has existentials
1576 -- it's possible that the join point will be abstracted over
1577 -- type varaibles as well as term variables.
1578 -- Example: Suppose we have
1579 -- data T = forall t. C [t]
1581 -- case (case e of ...) of
1582 -- C t xs::[t] -> rhs
1583 -- We get the join point
1584 -- let j :: forall t. [t] -> ...
1585 -- j = /\t \xs::[t] -> rhs
1587 -- case (case e of ...) of
1588 -- C t xs::[t] -> j t xs
1591 -- We make the lambdas into one-shot-lambdas. The
1592 -- join point is sure to be applied at most once, and doing so
1593 -- prevents the body of the join point being floated out by
1594 -- the full laziness pass
1595 really_final_bndrs = map one_shot final_bndrs'
1596 one_shot v | isId v = setOneShotLambda v
1599 returnSmpl ([NonRec join_bndr (mkLams really_final_bndrs rhs')],
1600 (con, bndrs, mkApps (Var join_bndr) final_args))