Join-point refactoring
[ghc.git] / compiler / simplCore / Simplify.hs
1 {-
2 (c) The AQUA Project, Glasgow University, 1993-1998
3
4 \section[Simplify]{The main module of the simplifier}
5 -}
6
7 {-# LANGUAGE CPP #-}
8
9 module Simplify ( simplTopBinds, simplExpr, simplRules ) where
10
11 #include "HsVersions.h"
12
13 import DynFlags
14 import SimplMonad
15 import Type hiding ( substTy, substTyVar, extendTvSubst, extendCvSubst )
16 import SimplEnv
17 import SimplUtils
18 import OccurAnal ( occurAnalyseExpr )
19 import FamInstEnv ( FamInstEnv )
20 import Literal ( litIsLifted ) --, mkMachInt ) -- temporalily commented out. See #8326
21 import Id
22 import MkId ( seqId )
23 import MkCore ( mkImpossibleExpr, castBottomExpr )
24 import IdInfo
25 import Name ( Name, mkSystemVarName, isExternalName, getOccFS )
26 import Coercion hiding ( substCo, substCoVar )
27 import OptCoercion ( optCoercion )
28 import FamInstEnv ( topNormaliseType_maybe )
29 import DataCon ( DataCon, dataConWorkId, dataConRepStrictness, dataConRepArgTys )
30 --import TyCon ( isEnumerationTyCon ) -- temporalily commented out. See #8326
31 import CoreMonad ( Tick(..), SimplifierMode(..) )
32 import CoreSyn
33 import Demand ( StrictSig(..), dmdTypeDepth, isStrictDmd )
34 import PprCore ( pprCoreExpr )
35 import CoreUnfold
36 import CoreUtils
37 import CoreArity
38 import CoreOpt ( pushCoTyArg, pushCoValArg
39 , joinPointBinding_maybe, joinPointBindings_maybe )
40 --import PrimOp ( tagToEnumKey ) -- temporalily commented out. See #8326
41 import Rules ( mkRuleInfo, lookupRule, getRules )
42 --import TysPrim ( intPrimTy ) -- temporalily commented out. See #8326
43 import BasicTypes ( TopLevelFlag(..), isNotTopLevel, isTopLevel,
44 RecFlag(..) )
45 import MonadUtils ( foldlM, mapAccumLM, liftIO )
46 import Maybes ( isJust, fromJust, orElse, catMaybes )
47 --import Unique ( hasKey ) -- temporalily commented out. See #8326
48 import Control.Monad
49 import Outputable
50 import FastString
51 import Pair
52 import Util
53 import ErrUtils
54 import Module ( moduleName, pprModuleName )
55
56 {-
57 The guts of the simplifier is in this module, but the driver loop for
58 the simplifier is in SimplCore.hs.
59
60
61 -----------------------------------------
62 *** IMPORTANT NOTE ***
63 -----------------------------------------
64 The simplifier used to guarantee that the output had no shadowing, but
65 it does not do so any more. (Actually, it never did!) The reason is
66 documented with simplifyArgs.
67
68
69 -----------------------------------------
70 *** IMPORTANT NOTE ***
71 -----------------------------------------
72 Many parts of the simplifier return a bunch of "floats" as well as an
73 expression. This is wrapped as a datatype SimplUtils.FloatsWith.
74
75 All "floats" are let-binds, not case-binds, but some non-rec lets may
76 be unlifted (with RHS ok-for-speculation).
77
78
79
80 -----------------------------------------
81 ORGANISATION OF FUNCTIONS
82 -----------------------------------------
83 simplTopBinds
84 - simplify all top-level binders
85 - for NonRec, call simplRecOrTopPair
86 - for Rec, call simplRecBind
87
88
89 ------------------------------
90 simplExpr (applied lambda) ==> simplNonRecBind
91 simplExpr (Let (NonRec ...) ..) ==> simplNonRecBind
92 simplExpr (Let (Rec ...) ..) ==> simplify binders; simplRecBind
93
94 ------------------------------
95 simplRecBind [binders already simplfied]
96 - use simplRecOrTopPair on each pair in turn
97
98 simplRecOrTopPair [binder already simplified]
99 Used for: recursive bindings (top level and nested)
100 top-level non-recursive bindings
101 Returns:
102 - check for PreInlineUnconditionally
103 - simplLazyBind
104
105 simplNonRecBind
106 Used for: non-top-level non-recursive bindings
107 beta reductions (which amount to the same thing)
108 Because it can deal with strict arts, it takes a
109 "thing-inside" and returns an expression
110
111 - check for PreInlineUnconditionally
112 - simplify binder, including its IdInfo
113 - if strict binding
114 simplStrictArg
115 mkAtomicArgs
116 completeNonRecX
117 else
118 simplLazyBind
119 addFloats
120
121 simplNonRecX: [given a *simplified* RHS, but an *unsimplified* binder]
122 Used for: binding case-binder and constr args in a known-constructor case
123 - check for PreInLineUnconditionally
124 - simplify binder
125 - completeNonRecX
126
127 ------------------------------
128 simplLazyBind: [binder already simplified, RHS not]
129 Used for: recursive bindings (top level and nested)
130 top-level non-recursive bindings
131 non-top-level, but *lazy* non-recursive bindings
132 [must not be strict or unboxed]
133 Returns floats + an augmented environment, not an expression
134 - substituteIdInfo and add result to in-scope
135 [so that rules are available in rec rhs]
136 - simplify rhs
137 - mkAtomicArgs
138 - float if exposes constructor or PAP
139 - completeBind
140
141
142 completeNonRecX: [binder and rhs both simplified]
143 - if the the thing needs case binding (unlifted and not ok-for-spec)
144 build a Case
145 else
146 completeBind
147 addFloats
148
149 completeBind: [given a simplified RHS]
150 [used for both rec and non-rec bindings, top level and not]
151 - try PostInlineUnconditionally
152 - add unfolding [this is the only place we add an unfolding]
153 - add arity
154
155
156
157 Right hand sides and arguments
158 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
159 In many ways we want to treat
160 (a) the right hand side of a let(rec), and
161 (b) a function argument
162 in the same way. But not always! In particular, we would
163 like to leave these arguments exactly as they are, so they
164 will match a RULE more easily.
165
166 f (g x, h x)
167 g (+ x)
168
169 It's harder to make the rule match if we ANF-ise the constructor,
170 or eta-expand the PAP:
171
172 f (let { a = g x; b = h x } in (a,b))
173 g (\y. + x y)
174
175 On the other hand if we see the let-defns
176
177 p = (g x, h x)
178 q = + x
179
180 then we *do* want to ANF-ise and eta-expand, so that p and q
181 can be safely inlined.
182
183 Even floating lets out is a bit dubious. For let RHS's we float lets
184 out if that exposes a value, so that the value can be inlined more vigorously.
185 For example
186
187 r = let x = e in (x,x)
188
189 Here, if we float the let out we'll expose a nice constructor. We did experiments
190 that showed this to be a generally good thing. But it was a bad thing to float
191 lets out unconditionally, because that meant they got allocated more often.
192
193 For function arguments, there's less reason to expose a constructor (it won't
194 get inlined). Just possibly it might make a rule match, but I'm pretty skeptical.
195 So for the moment we don't float lets out of function arguments either.
196
197
198 Eta expansion
199 ~~~~~~~~~~~~~~
200 For eta expansion, we want to catch things like
201
202 case e of (a,b) -> \x -> case a of (p,q) -> \y -> r
203
204 If the \x was on the RHS of a let, we'd eta expand to bring the two
205 lambdas together. And in general that's a good thing to do. Perhaps
206 we should eta expand wherever we find a (value) lambda? Then the eta
207 expansion at a let RHS can concentrate solely on the PAP case.
208
209
210 Case-of-case and join points
211 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
212 When we perform the case-of-case transform (or otherwise push continuations
213 inward), we want to treat join points specially. Since they're always
214 tail-called and we want to maintain this invariant, we can do this (for any
215 evaluation context E):
216
217 E[join j = e
218 in case ... of
219 A -> jump j 1
220 B -> jump j 2
221 C -> f 3]
222
223 -->
224
225 join j = E[e]
226 in case ... of
227 A -> jump j 1
228 B -> jump j 2
229 C -> E[f 3]
230
231 As is evident from the example, there are two components to this behavior:
232
233 1. When entering the RHS of a join point, copy the context inside.
234 2. When a join point is invoked, discard the outer context.
235
236 Clearly we need to be very careful here to remain consistent---neither part is
237 optional!
238
239 ************************************************************************
240 * *
241 \subsection{Bindings}
242 * *
243 ************************************************************************
244 -}
245
246 simplTopBinds :: SimplEnv -> [InBind] -> SimplM SimplEnv
247
248 simplTopBinds env0 binds0
249 = do { -- Put all the top-level binders into scope at the start
250 -- so that if a transformation rule has unexpectedly brought
251 -- anything into scope, then we don't get a complaint about that.
252 -- It's rather as if the top-level binders were imported.
253 -- See note [Glomming] in OccurAnal.
254 ; env1 <- simplRecBndrs env0 (bindersOfBinds binds0)
255 ; env2 <- simpl_binds env1 binds0
256 ; freeTick SimplifierDone
257 ; return env2 }
258 where
259 -- We need to track the zapped top-level binders, because
260 -- they should have their fragile IdInfo zapped (notably occurrence info)
261 -- That's why we run down binds and bndrs' simultaneously.
262 --
263 simpl_binds :: SimplEnv -> [InBind] -> SimplM SimplEnv
264 simpl_binds env [] = return env
265 simpl_binds env (bind:binds) = do { env' <- simpl_bind env bind
266 ; simpl_binds env' binds }
267
268 simpl_bind env (Rec pairs) = simplRecBind env TopLevel Nothing pairs
269 simpl_bind env (NonRec b r) = do { (env', b') <- addBndrRules env b (lookupRecBndr env b)
270 ; simplRecOrTopPair env' TopLevel
271 NonRecursive Nothing
272 b b' r }
273
274 {-
275 ************************************************************************
276 * *
277 \subsection{Lazy bindings}
278 * *
279 ************************************************************************
280
281 simplRecBind is used for
282 * recursive bindings only
283 -}
284
285 simplRecBind :: SimplEnv -> TopLevelFlag -> Maybe SimplCont
286 -> [(InId, InExpr)]
287 -> SimplM SimplEnv
288 simplRecBind env0 top_lvl mb_cont pairs0
289 = do { (env_with_info, triples) <- mapAccumLM add_rules env0 pairs0
290 ; env1 <- go (zapFloats env_with_info) triples
291 ; return (env0 `addRecFloats` env1) }
292 -- addRecFloats adds the floats from env1,
293 -- _and_ updates env0 with the in-scope set from env1
294 where
295 add_rules :: SimplEnv -> (InBndr,InExpr) -> SimplM (SimplEnv, (InBndr, OutBndr, InExpr))
296 -- Add the (substituted) rules to the binder
297 add_rules env (bndr, rhs)
298 = do { (env', bndr') <- addBndrRules env bndr (lookupRecBndr env bndr)
299 ; return (env', (bndr, bndr', rhs)) }
300
301 go env [] = return env
302
303 go env ((old_bndr, new_bndr, rhs) : pairs)
304 = do { env' <- simplRecOrTopPair env top_lvl Recursive mb_cont
305 old_bndr new_bndr rhs
306 ; go env' pairs }
307
308 {-
309 simplOrTopPair is used for
310 * recursive bindings (whether top level or not)
311 * top-level non-recursive bindings
312
313 It assumes the binder has already been simplified, but not its IdInfo.
314 -}
315
316 simplRecOrTopPair :: SimplEnv
317 -> TopLevelFlag -> RecFlag -> Maybe SimplCont
318 -> InId -> OutBndr -> InExpr -- Binder and rhs
319 -> SimplM SimplEnv -- Returns an env that includes the binding
320
321 simplRecOrTopPair env top_lvl is_rec mb_cont old_bndr new_bndr rhs
322 = do { dflags <- getDynFlags
323 ; trace_bind dflags $
324 if preInlineUnconditionally dflags env top_lvl old_bndr rhs
325 -- Check for unconditional inline
326 then do tick (PreInlineUnconditionally old_bndr)
327 return (extendIdSubst env old_bndr (mkContEx env rhs))
328 else simplBind env top_lvl is_rec mb_cont old_bndr new_bndr rhs env }
329 where
330 trace_bind dflags thing_inside
331 | not (dopt Opt_D_verbose_core2core dflags)
332 = thing_inside
333 | otherwise
334 = pprTrace "SimplBind" (ppr old_bndr) thing_inside
335 -- trace_bind emits a trace for each top-level binding, which
336 -- helps to locate the tracing for inlining and rule firing
337
338 {-
339 simplBind is used for
340 * [simplRecOrTopPair] recursive bindings (whether top level or not)
341 * [simplRecOrTopPair] top-level non-recursive bindings
342 * [simplNonRecE] non-top-level *lazy* non-recursive bindings
343
344 Nota bene:
345 1. It assumes that the binder is *already* simplified,
346 and is in scope, and its IdInfo too, except unfolding
347
348 2. It assumes that the binder type is lifted.
349
350 3. It does not check for pre-inline-unconditionally;
351 that should have been done already.
352 -}
353
354 simplBind :: SimplEnv
355 -> TopLevelFlag -> RecFlag -> Maybe SimplCont
356 -> InId -> OutId -- Binder, both pre-and post simpl
357 -- Can be a JoinId
358 -- The OutId has IdInfo, except arity, unfolding
359 -- Ids only, no TyVars
360 -> InExpr -> SimplEnv -- The RHS and its environment
361 -> SimplM SimplEnv
362 simplBind env top_lvl is_rec mb_cont bndr bndr1 rhs rhs_se
363 | ASSERT( isId bndr1 )
364 isJoinId bndr1
365 = ASSERT(isNotTopLevel top_lvl && isJust mb_cont)
366 simplJoinBind env is_rec (fromJust mb_cont) bndr bndr1 rhs rhs_se
367 | otherwise
368 = simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
369
370 simplLazyBind :: SimplEnv
371 -> TopLevelFlag -> RecFlag
372 -> InId -> OutId -- Binder, both pre-and post simpl
373 -- Not a JoinId
374 -- The OutId has IdInfo, except arity, unfolding
375 -- Ids only, no TyVars
376 -> InExpr -> SimplEnv -- The RHS and its environment
377 -> SimplM SimplEnv
378 -- Precondition: not a JoinId
379 -- Precondition: rhs obeys the let/app invariant
380 -- NOT used for JoinIds
381 simplLazyBind env top_lvl is_rec bndr bndr1 rhs rhs_se
382 = ASSERT( isId bndr )
383 ASSERT2( not (isJoinId bndr), ppr bndr )
384 -- pprTrace "simplLazyBind" ((ppr bndr <+> ppr bndr1) $$ ppr rhs $$ ppr (seIdSubst rhs_se)) $
385 do { let rhs_env = rhs_se `setInScopeAndZapFloats` env
386 (tvs, body) = case collectTyAndValBinders rhs of
387 (tvs, [], body)
388 | surely_not_lam body -> (tvs, body)
389 _ -> ([], rhs)
390
391 surely_not_lam (Lam {}) = False
392 surely_not_lam (Tick t e)
393 | not (tickishFloatable t) = surely_not_lam e
394 -- eta-reduction could float
395 surely_not_lam _ = True
396 -- Do not do the "abstract tyyvar" thing if there's
397 -- a lambda inside, because it defeats eta-reduction
398 -- f = /\a. \x. g a x
399 -- should eta-reduce.
400
401
402 ; (body_env, tvs') <- simplBinders rhs_env tvs
403 -- See Note [Floating and type abstraction] in SimplUtils
404
405 -- Simplify the RHS
406 ; let rhs_cont = mkRhsStop (substTy body_env (exprType body))
407 ; (body_env0, body0) <- simplExprF body_env body rhs_cont
408 ; let (body_env1, body1) = wrapJoinFloatsX body_env0 body0
409
410 -- ANF-ise a constructor or PAP rhs
411 ; (body_env2, body2) <- prepareRhs top_lvl body_env1 bndr1 body1
412
413 -- We need body_env2 for its let-floats (only);
414 -- we've dealt with its join-floats, which are now empty
415 ; (env', rhs')
416 <- if not (doFloatFromRhs top_lvl is_rec False body2 body_env2)
417 then -- No floating, revert to body1
418 do { rhs' <- mkLam env tvs' (wrapFloats body_env1 body1) rhs_cont
419 ; return (env, rhs') }
420
421 else if null tvs then -- Simple floating
422 do { tick LetFloatFromLet
423 ; return (addLetFloats env body_env2, body2) }
424
425 else -- Do type-abstraction first
426 do { tick LetFloatFromLet
427 ; (poly_binds, body3) <- abstractFloats tvs' body_env2 body2
428 ; rhs' <- mkLam env tvs' body3 rhs_cont
429 ; env' <- foldlM (addPolyBind top_lvl) env poly_binds
430 ; return (env', rhs') }
431
432 ; completeBind env' top_lvl is_rec Nothing bndr bndr1 rhs' }
433
434 simplJoinBind :: SimplEnv
435 -> RecFlag
436 -> SimplCont
437 -> InId -> OutId -- Binder, both pre-and post simpl
438 -- The OutId has IdInfo, except arity,
439 -- unfolding
440 -> InExpr -> SimplEnv -- The RHS and its environment
441 -> SimplM SimplEnv
442 simplJoinBind env is_rec cont bndr bndr1 rhs rhs_se
443 = -- pprTrace "simplLazyBind" ((ppr bndr <+> ppr bndr1) $$
444 -- ppr rhs $$ ppr (seIdSubst rhs_se)) $
445 do { let rhs_env = rhs_se `setInScopeAndZapFloats` env
446 ; rhs' <- simplJoinRhs rhs_env bndr rhs cont
447 ; completeBind env NotTopLevel is_rec (Just cont) bndr bndr1 rhs' }
448
449 {-
450 A specialised variant of simplNonRec used when the RHS is already simplified,
451 notably in knownCon. It uses case-binding where necessary.
452 -}
453
454 simplNonRecX :: SimplEnv
455 -> InId -- Old binder; not a JoinId
456 -> OutExpr -- Simplified RHS
457 -> SimplM SimplEnv
458 -- Precondition: rhs satisfies the let/app invariant
459 simplNonRecX env bndr new_rhs
460 | ASSERT2( not (isJoinId bndr), ppr bndr )
461 isDeadBinder bndr -- Not uncommon; e.g. case (a,b) of c { (p,q) -> p }
462 = return env -- Here c is dead, and we avoid creating
463 -- the binding c = (a,b)
464
465 | Coercion co <- new_rhs
466 = return (extendCvSubst env bndr co)
467
468 | otherwise
469 = do { (env', bndr') <- simplBinder env bndr
470 ; completeNonRecX NotTopLevel env' (isStrictId bndr) bndr bndr' new_rhs }
471 -- simplNonRecX is only used for NotTopLevel things
472
473 completeNonRecX :: TopLevelFlag -> SimplEnv
474 -> Bool
475 -> InId -- Old binder; not a JoinId
476 -> OutId -- New binder
477 -> OutExpr -- Simplified RHS
478 -> SimplM SimplEnv -- The new binding extends the seLetFloats
479 -- of the resulting SimpleEnv
480 -- Precondition: rhs satisfies the let/app invariant
481 -- See Note [CoreSyn let/app invariant] in CoreSyn
482
483 completeNonRecX top_lvl env is_strict old_bndr new_bndr new_rhs
484 = ASSERT2( not (isJoinId new_bndr), ppr new_bndr )
485 do { (env1, rhs1) <- prepareRhs top_lvl (zapFloats env) new_bndr new_rhs
486 ; (env2, rhs2) <-
487 if doFloatFromRhs NotTopLevel NonRecursive is_strict rhs1 env1
488 then do { tick LetFloatFromLet
489 ; return (addLetFloats env env1, rhs1) } -- Add the floats to the main env
490 else return (env, wrapFloats env1 rhs1) -- Wrap the floats around the RHS
491 ; completeBind env2 NotTopLevel NonRecursive Nothing
492 old_bndr new_bndr rhs2 }
493
494 {- No, no, no! Do not try preInlineUnconditionally in completeNonRecX
495 Doing so risks exponential behaviour, because new_rhs has been simplified once already
496 In the cases described by the following comment, postInlineUnconditionally will
497 catch many of the relevant cases.
498 -- This happens; for example, the case_bndr during case of
499 -- known constructor: case (a,b) of x { (p,q) -> ... }
500 -- Here x isn't mentioned in the RHS, so we don't want to
501 -- create the (dead) let-binding let x = (a,b) in ...
502 --
503 -- Similarly, single occurrences can be inlined vigourously
504 -- e.g. case (f x, g y) of (a,b) -> ....
505 -- If a,b occur once we can avoid constructing the let binding for them.
506
507 Furthermore in the case-binding case preInlineUnconditionally risks extra thunks
508 -- Consider case I# (quotInt# x y) of
509 -- I# v -> let w = J# v in ...
510 -- If we gaily inline (quotInt# x y) for v, we end up building an
511 -- extra thunk:
512 -- let w = J# (quotInt# x y) in ...
513 -- because quotInt# can fail.
514
515 | preInlineUnconditionally env NotTopLevel bndr new_rhs
516 = thing_inside (extendIdSubst env bndr (DoneEx new_rhs))
517 -}
518
519 ----------------------------------
520 {- Note [Avoiding exponential behaviour]
521 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
522 One way in which we can get exponential behaviour is if we simplify a
523 big expression, and the re-simplify it -- and then this happens in a
524 deeply-nested way. So we must be jolly careful about re-simplifying
525 an expression. That is why completeNonRecX does not try
526 preInlineUnconditionally.
527
528 Example:
529 f BIG, where f has a RULE
530 Then
531 * We simplify BIG before trying the rule; but the rule does not fire
532 * We inline f = \x. x True
533 * So if we did preInlineUnconditionally we'd re-simplify (BIG True)
534
535 However, if BIG has /not/ already been simplified, we'd /like/ to
536 simplify BIG True; maybe good things happen. That is why
537
538 * simplLam has
539 - a case for (isSimplified dup), which goes via simplNonRecX, and
540 - a case for the un-simplified case, which goes via simplNonRecE
541
542 * We go to some efforts to avoid unnecessarily simplifying ApplyToVal,
543 in at least two places
544 - In simplCast/addCoerce, where we check for isReflCo
545 - In rebuildCall we avoid simplifying arguments before we have to
546 (see Note [Trying rewrite rules])
547
548 Note [prepareRhs]
549 ~~~~~~~~~~~~~~~~~
550 prepareRhs takes a putative RHS, checks whether it's a PAP or
551 constructor application and, if so, converts it to ANF, so that the
552 resulting thing can be inlined more easily. Thus
553 x = (f a, g b)
554 becomes
555 t1 = f a
556 t2 = g b
557 x = (t1,t2)
558
559 We also want to deal well cases like this
560 v = (f e1 `cast` co) e2
561 Here we want to make e1,e2 trivial and get
562 x1 = e1; x2 = e2; v = (f x1 `cast` co) v2
563 That's what the 'go' loop in prepareRhs does
564 -}
565
566 prepareRhs :: TopLevelFlag -> SimplEnv -> OutId -> OutExpr -> SimplM (SimplEnv, OutExpr)
567 -- See Note [prepareRhs]
568 -- Adds new floats to the env iff that allows us to return a good RHS
569 -- See Note [prepareRhs]
570 prepareRhs top_lvl env id (Cast rhs co) -- Note [Float coercions]
571 | Pair ty1 _ty2 <- coercionKind co -- Do *not* do this if rhs has an unlifted type
572 , not (isUnliftedType ty1) -- see Note [Float coercions (unlifted)]
573 = do { (env', rhs') <- makeTrivialWithInfo top_lvl env (getOccFS id) sanitised_info rhs
574 ; return (env', Cast rhs' co) }
575 where
576 sanitised_info = vanillaIdInfo `setStrictnessInfo` strictnessInfo info
577 `setDemandInfo` demandInfo info
578 info = idInfo id
579
580 prepareRhs top_lvl env0 id rhs0
581 = do { (_is_exp, env1, rhs1) <- go 0 env0 rhs0
582 ; return (env1, rhs1) }
583 where
584 go n_val_args env (Cast rhs co)
585 = do { (is_exp, env', rhs') <- go n_val_args env rhs
586 ; return (is_exp, env', Cast rhs' co) }
587 go n_val_args env (App fun (Type ty))
588 = do { (is_exp, env', rhs') <- go n_val_args env fun
589 ; return (is_exp, env', App rhs' (Type ty)) }
590 go n_val_args env (App fun arg)
591 = do { (is_exp, env', fun') <- go (n_val_args+1) env fun
592 ; case is_exp of
593 True -> do { (env'', arg') <- makeTrivial top_lvl env' (getOccFS id) arg
594 ; return (True, env'', App fun' arg') }
595 False -> return (False, env, App fun arg) }
596 go n_val_args env (Var fun)
597 = return (is_exp, env, Var fun)
598 where
599 is_exp = isExpandableApp fun n_val_args -- The fun a constructor or PAP
600 -- See Note [CONLIKE pragma] in BasicTypes
601 -- The definition of is_exp should match that in
602 -- OccurAnal.occAnalApp
603
604 go n_val_args env (Tick t rhs)
605 -- We want to be able to float bindings past this
606 -- tick. Non-scoping ticks don't care.
607 | tickishScoped t == NoScope
608 = do { (is_exp, env', rhs') <- go n_val_args env rhs
609 ; return (is_exp, env', Tick t rhs') }
610
611 -- On the other hand, for scoping ticks we need to be able to
612 -- copy them on the floats, which in turn is only allowed if
613 -- we can obtain non-counting ticks.
614 | (not (tickishCounts t) || tickishCanSplit t)
615 = do { (is_exp, env', rhs') <- go n_val_args (zapFloats env) rhs
616 -- env' has the extra let-bindings from
617 -- the makeTrivial calls in 'go'; no join floats
618 ; let tickIt (id, expr)
619 -- we have to take care not to tick top-level literal
620 -- strings. See Note [CoreSyn top-level string literals].
621 | isTopLevel top_lvl && exprIsLiteralString expr
622 = (id, expr)
623 | otherwise
624 = (id, mkTick (mkNoCount t) expr)
625 floats' = seLetFloats env `addFlts`
626 mapFloats (seLetFloats env') tickIt
627 ; return (is_exp, env' { seLetFloats = floats' }, Tick t rhs') }
628
629 go _ env other
630 = return (False, env, other)
631
632 {-
633 Note [Float coercions]
634 ~~~~~~~~~~~~~~~~~~~~~~
635 When we find the binding
636 x = e `cast` co
637 we'd like to transform it to
638 x' = e
639 x = x `cast` co -- A trivial binding
640 There's a chance that e will be a constructor application or function, or something
641 like that, so moving the coercion to the usage site may well cancel the coercions
642 and lead to further optimisation. Example:
643
644 data family T a :: *
645 data instance T Int = T Int
646
647 foo :: Int -> Int -> Int
648 foo m n = ...
649 where
650 x = T m
651 go 0 = 0
652 go n = case x of { T m -> go (n-m) }
653 -- This case should optimise
654
655 Note [Preserve strictness when floating coercions]
656 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
657 In the Note [Float coercions] transformation, keep the strictness info.
658 Eg
659 f = e `cast` co -- f has strictness SSL
660 When we transform to
661 f' = e -- f' also has strictness SSL
662 f = f' `cast` co -- f still has strictness SSL
663
664 Its not wrong to drop it on the floor, but better to keep it.
665
666 Note [Float coercions (unlifted)]
667 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
668 BUT don't do [Float coercions] if 'e' has an unlifted type.
669 This *can* happen:
670
671 foo :: Int = (error (# Int,Int #) "urk")
672 `cast` CoUnsafe (# Int,Int #) Int
673
674 If do the makeTrivial thing to the error call, we'll get
675 foo = case error (# Int,Int #) "urk" of v -> v `cast` ...
676 But 'v' isn't in scope!
677
678 These strange casts can happen as a result of case-of-case
679 bar = case (case x of { T -> (# 2,3 #); F -> error "urk" }) of
680 (# p,q #) -> p+q
681 -}
682
683 makeTrivialArg :: SimplEnv -> ArgSpec -> SimplM (SimplEnv, ArgSpec)
684 makeTrivialArg env (ValArg e) = do
685 { (env', e') <- makeTrivial NotTopLevel env (fsLit "arg") e
686 ; return (env', ValArg e') }
687 makeTrivialArg env arg = return (env, arg) -- CastBy, TyArg
688
689 makeTrivial :: TopLevelFlag -> SimplEnv
690 -> FastString -- ^ a "friendly name" to build the new binder from
691 -> OutExpr -> SimplM (SimplEnv, OutExpr)
692 -- Binds the expression to a variable, if it's not trivial, returning the variable
693 makeTrivial top_lvl env context expr =
694 makeTrivialWithInfo top_lvl env context vanillaIdInfo expr
695
696 makeTrivialWithInfo :: TopLevelFlag -> SimplEnv
697 -> FastString
698 -- ^ a "friendly name" to build the new binder from
699 -> IdInfo -> OutExpr -> SimplM (SimplEnv, OutExpr)
700 -- Propagate strictness and demand info to the new binder
701 -- Note [Preserve strictness when floating coercions]
702 -- Returned SimplEnv has same substitution as incoming one
703 makeTrivialWithInfo top_lvl env context info expr
704 | exprIsTrivial expr -- Already trivial
705 || not (bindingOk top_lvl expr expr_ty) -- Cannot trivialise
706 -- See Note [Cannot trivialise]
707 = return (env, expr)
708
709 | otherwise -- See Note [Take care] below
710 = do { uniq <- getUniqueM
711 ; let name = mkSystemVarName uniq context
712 var = mkLocalIdOrCoVarWithInfo name expr_ty info
713 ; env' <- completeNonRecX top_lvl env False var var expr
714 ; expr' <- simplVar env' var
715 ; return (env', expr') }
716 -- The simplVar is needed because we're constructing a new binding
717 -- a = rhs
718 -- And if rhs is of form (rhs1 |> co), then we might get
719 -- a1 = rhs1
720 -- a = a1 |> co
721 -- and now a's RHS is trivial and can be substituted out, and that
722 -- is what completeNonRecX will do
723 -- To put it another way, it's as if we'd simplified
724 -- let var = e in var
725 where
726 expr_ty = exprType expr
727
728 bindingOk :: TopLevelFlag -> CoreExpr -> Type -> Bool
729 -- True iff we can have a binding of this expression at this level
730 -- Precondition: the type is the type of the expression
731 bindingOk top_lvl expr expr_ty
732 | isTopLevel top_lvl = exprIsTopLevelBindable expr expr_ty
733 | otherwise = True
734
735 {-
736 Note [Cannot trivialise]
737 ~~~~~~~~~~~~~~~~~~~~~~~~
738 Consider tih
739 f :: Int -> Addr#
740
741 foo :: Bar
742 foo = Bar (f 3)
743
744 Then we can't ANF-ise foo, even though we'd like to, because
745 we can't make a top-level binding for the Addr# (f 3). And if
746 so we don't want to turn it into
747 foo = let x = f 3 in Bar x
748 because we'll just end up inlining x back, and that makes the
749 simplifier loop. Better not to ANF-ise it at all.
750
751 Literal strings are an exception.
752
753 foo = Ptr "blob"#
754
755 We want to turn this into:
756
757 foo1 = "blob"#
758 foo = Ptr foo1
759
760 See Note [CoreSyn top-level string literals] in CoreSyn.
761
762 ************************************************************************
763 * *
764 \subsection{Completing a lazy binding}
765 * *
766 ************************************************************************
767
768 completeBind
769 * deals only with Ids, not TyVars
770 * takes an already-simplified binder and RHS
771 * is used for both recursive and non-recursive bindings
772 * is used for both top-level and non-top-level bindings
773
774 It does the following:
775 - tries discarding a dead binding
776 - tries PostInlineUnconditionally
777 - add unfolding [this is the only place we add an unfolding]
778 - add arity
779
780 It does *not* attempt to do let-to-case. Why? Because it is used for
781 - top-level bindings (when let-to-case is impossible)
782 - many situations where the "rhs" is known to be a WHNF
783 (so let-to-case is inappropriate).
784
785 Nor does it do the atomic-argument thing
786 -}
787
788 completeBind :: SimplEnv
789 -> TopLevelFlag -- Flag stuck into unfolding
790 -> RecFlag -- Recursive binding?
791 -> Maybe SimplCont -- Required only for join point
792 -> InId -- Old binder
793 -> OutId -> OutExpr -- New binder and RHS
794 -> SimplM SimplEnv
795 -- completeBind may choose to do its work
796 -- * by extending the substitution (e.g. let x = y in ...)
797 -- * or by adding to the floats in the envt
798 --
799 -- Binder /can/ be a JoinId
800 -- Precondition: rhs obeys the let/app invariant
801 completeBind env top_lvl is_rec mb_cont old_bndr new_bndr new_rhs
802 | isCoVar old_bndr
803 = case new_rhs of
804 Coercion co -> return (extendCvSubst env old_bndr co)
805 _ -> return (addNonRec env new_bndr new_rhs)
806
807 | otherwise
808 = ASSERT( isId new_bndr )
809 do { let old_info = idInfo old_bndr
810 old_unf = unfoldingInfo old_info
811 occ_info = occInfo old_info
812
813 -- Do eta-expansion on the RHS of the binding
814 -- See Note [Eta-expanding at let bindings] in SimplUtils
815 ; (new_arity, final_rhs) <- if isJoinId new_bndr
816 then return (manifestArity new_rhs, new_rhs)
817 -- Note [Don't eta-expand join points]
818 else tryEtaExpandRhs env is_rec
819 new_bndr new_rhs
820
821 -- Simplify the unfolding
822 ; new_unfolding <- simplLetUnfolding env top_lvl mb_cont old_bndr
823 final_rhs old_unf
824
825 ; dflags <- getDynFlags
826 ; if postInlineUnconditionally dflags env top_lvl new_bndr occ_info
827 final_rhs new_unfolding
828
829 -- Inline and discard the binding
830 then do { tick (PostInlineUnconditionally old_bndr)
831 ; return (extendIdSubst env old_bndr
832 (DoneEx final_rhs (isJoinId_maybe new_bndr))) }
833 -- Use the substitution to make quite, quite sure that the
834 -- substitution will happen, since we are going to discard the binding
835 else
836 do { let info1 = idInfo new_bndr `setArityInfo` new_arity
837
838 -- Unfolding info: Note [Setting the new unfolding]
839 info2 = info1 `setUnfoldingInfo` new_unfolding
840
841 -- Demand info: Note [Setting the demand info]
842 --
843 -- We also have to nuke demand info if for some reason
844 -- eta-expansion *reduces* the arity of the binding to less
845 -- than that of the strictness sig. This can happen: see Note [Arity decrease].
846 info3 | isEvaldUnfolding new_unfolding
847 || (case strictnessInfo info2 of
848 StrictSig dmd_ty -> new_arity < dmdTypeDepth dmd_ty)
849 = zapDemandInfo info2 `orElse` info2
850 | otherwise
851 = info2
852
853 -- Zap call arity info. We have used it by now (via
854 -- `tryEtaExpandRhs`), and the simplifier can invalidate this
855 -- information, leading to broken code later (e.g. #13479)
856 info4 = zapCallArityInfo info3
857
858 final_id = new_bndr `setIdInfo` info4
859
860 ; -- pprTrace "Binding" (ppr final_id <+> ppr new_unfolding) $
861 return (addNonRec env final_id final_rhs) } }
862 -- The addNonRec adds it to the in-scope set too
863
864 ------------------------------
865 addPolyBind :: TopLevelFlag -> SimplEnv -> OutBind -> SimplM SimplEnv
866 -- Add a new binding to the environment, complete with its unfolding
867 -- but *do not* do postInlineUnconditionally, because we have already
868 -- processed some of the scope of the binding
869 -- We still want the unfolding though. Consider
870 -- let
871 -- x = /\a. let y = ... in Just y
872 -- in body
873 -- Then we float the y-binding out (via abstractFloats and addPolyBind)
874 -- but 'x' may well then be inlined in 'body' in which case we'd like the
875 -- opportunity to inline 'y' too.
876 --
877 -- INVARIANT: the arity is correct on the incoming binders
878
879 addPolyBind top_lvl env (NonRec poly_id rhs)
880 = do { unfolding <- simplLetUnfolding env top_lvl Nothing poly_id rhs
881 noUnfolding
882 -- Assumes that poly_id did not have an INLINE prag
883 -- which is perhaps wrong. ToDo: think about this
884 ; let final_id = setIdInfo poly_id $
885 idInfo poly_id `setUnfoldingInfo` unfolding
886
887 ; return (addNonRec env final_id rhs) }
888
889 addPolyBind _ env bind@(Rec _)
890 = return (extendFloats env bind)
891 -- Hack: letrecs are more awkward, so we extend "by steam"
892 -- without adding unfoldings etc. At worst this leads to
893 -- more simplifier iterations
894
895 {- Note [Arity decrease]
896 ~~~~~~~~~~~~~~~~~~~~~~~~
897 Generally speaking the arity of a binding should not decrease. But it *can*
898 legitimately happen because of RULES. Eg
899 f = g Int
900 where g has arity 2, will have arity 2. But if there's a rewrite rule
901 g Int --> h
902 where h has arity 1, then f's arity will decrease. Here's a real-life example,
903 which is in the output of Specialise:
904
905 Rec {
906 $dm {Arity 2} = \d.\x. op d
907 {-# RULES forall d. $dm Int d = $s$dm #-}
908
909 dInt = MkD .... opInt ...
910 opInt {Arity 1} = $dm dInt
911
912 $s$dm {Arity 0} = \x. op dInt }
913
914 Here opInt has arity 1; but when we apply the rule its arity drops to 0.
915 That's why Specialise goes to a little trouble to pin the right arity
916 on specialised functions too.
917
918 Note [Setting the demand info]
919 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
920 If the unfolding is a value, the demand info may
921 go pear-shaped, so we nuke it. Example:
922 let x = (a,b) in
923 case x of (p,q) -> h p q x
924 Here x is certainly demanded. But after we've nuked
925 the case, we'll get just
926 let x = (a,b) in h a b x
927 and now x is not demanded (I'm assuming h is lazy)
928 This really happens. Similarly
929 let f = \x -> e in ...f..f...
930 After inlining f at some of its call sites the original binding may
931 (for example) be no longer strictly demanded.
932 The solution here is a bit ad hoc...
933
934 Note [Don't eta-expand join points]
935 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
936
937 Similarly to CPR (see Note [Don't CPR join points] in WorkWrap), a join point
938 stands well to gain from its outer binding's eta-expansion, and eta-expanding a
939 join point is fraught with issues like how to deal with a cast:
940
941 let join $j1 :: IO ()
942 $j1 = ...
943 $j2 :: Int -> IO ()
944 $j2 n = if n > 0 then $j1
945 else ...
946
947 =>
948
949 let join $j1 :: IO ()
950 $j1 = (\eta -> ...)
951 `cast` N:IO :: State# RealWorld -> (# State# RealWorld, ())
952 ~ IO ()
953 $j2 :: Int -> IO ()
954 $j2 n = (\eta -> if n > 0 then $j1
955 else ...)
956 `cast` N:IO :: State# RealWorld -> (# State# RealWorld, ())
957 ~ IO ()
958
959 The cast here can't be pushed inside the lambda (since it's not casting to a
960 function type), so the lambda has to stay, but it can't because it contains a
961 reference to a join point. In fact, $j2 can't be eta-expanded at all. Rather
962 than try and detect this situation (and whatever other situations crop up!), we
963 don't bother; again, any surrounding eta-expansion will improve these join
964 points anyway, since an outer cast can *always* be pushed inside. By the time
965 CorePrep comes around, the code is very likely to look more like this:
966
967 let join $j1 :: State# RealWorld -> (# State# RealWorld, ())
968 $j1 = (...) eta
969 $j2 :: Int -> State# RealWorld -> (# State# RealWorld, ())
970 $j2 = if n > 0 then $j1
971 else (...) eta
972
973 ************************************************************************
974 * *
975 \subsection[Simplify-simplExpr]{The main function: simplExpr}
976 * *
977 ************************************************************************
978
979 The reason for this OutExprStuff stuff is that we want to float *after*
980 simplifying a RHS, not before. If we do so naively we get quadratic
981 behaviour as things float out.
982
983 To see why it's important to do it after, consider this (real) example:
984
985 let t = f x
986 in fst t
987 ==>
988 let t = let a = e1
989 b = e2
990 in (a,b)
991 in fst t
992 ==>
993 let a = e1
994 b = e2
995 t = (a,b)
996 in
997 a -- Can't inline a this round, cos it appears twice
998 ==>
999 e1
1000
1001 Each of the ==> steps is a round of simplification. We'd save a
1002 whole round if we float first. This can cascade. Consider
1003
1004 let f = g d
1005 in \x -> ...f...
1006 ==>
1007 let f = let d1 = ..d.. in \y -> e
1008 in \x -> ...f...
1009 ==>
1010 let d1 = ..d..
1011 in \x -> ...(\y ->e)...
1012
1013 Only in this second round can the \y be applied, and it
1014 might do the same again.
1015 -}
1016
1017 simplExpr :: SimplEnv -> CoreExpr -> SimplM CoreExpr
1018 simplExpr env (Type ty)
1019 = do { ty' <- simplType env ty -- See Note [Avoiding space leaks in OutType]
1020 ; return (Type ty') }
1021
1022 simplExpr env expr
1023 = simplExprC env expr (mkBoringStop expr_out_ty)
1024 where
1025 expr_out_ty :: OutType
1026 expr_out_ty = substTy env (exprType expr)
1027 -- NB: Since 'expr' is term-valued, not (Type ty), this call
1028 -- to exprType will succeed. exprType fails on (Type ty).
1029
1030 simplExprC :: SimplEnv
1031 -> InExpr -- A term-valued expression, never (Type ty)
1032 -> SimplCont
1033 -> SimplM OutExpr
1034 -- Simplify an expression, given a continuation
1035 simplExprC env expr cont
1036 = -- pprTrace "simplExprC" (ppr expr $$ ppr cont {- $$ ppr (seIdSubst env) -} $$ ppr (seLetFloats env) ) $
1037 do { (env', expr') <- simplExprF (zapFloats env) expr cont
1038 ; -- pprTrace "simplExprC ret" (ppr expr $$ ppr expr') $
1039 -- pprTrace "simplExprC ret3" (ppr (seInScope env')) $
1040 -- pprTrace "simplExprC ret4" (ppr (seLetFloats env')) $
1041 return (wrapFloats env' expr') }
1042
1043 --------------------------------------------------
1044 simplExprF :: SimplEnv
1045 -> InExpr -- A term-valued expression, never (Type ty)
1046 -> SimplCont
1047 -> SimplM (SimplEnv, OutExpr)
1048
1049 simplExprF env e cont
1050 = {- pprTrace "simplExprF" (vcat
1051 [ ppr e
1052 , text "cont =" <+> ppr cont
1053 , text "inscope =" <+> ppr (seInScope env)
1054 , text "tvsubst =" <+> ppr (seTvSubst env)
1055 , text "idsubst =" <+> ppr (seIdSubst env)
1056 , text "cvsubst =" <+> ppr (seCvSubst env)
1057 {- , ppr (seLetFloats env) -}
1058 ]) $ -}
1059 simplExprF1 env e cont
1060
1061 simplExprF1 :: SimplEnv -> InExpr -> SimplCont
1062 -> SimplM (SimplEnv, OutExpr)
1063
1064 simplExprF1 _ (Type ty) _
1065 = pprPanic "simplExprF: type" (ppr ty)
1066 -- simplExprF does only with term-valued expressions
1067 -- The (Type ty) case is handled separately by simplExpr
1068 -- and by the other callers of simplExprF
1069
1070 simplExprF1 env (Var v) cont = simplIdF env v cont
1071 simplExprF1 env (Lit lit) cont = rebuild env (Lit lit) cont
1072 simplExprF1 env (Tick t expr) cont = simplTick env t expr cont
1073 simplExprF1 env (Cast body co) cont = simplCast env body co cont
1074 simplExprF1 env (Coercion co) cont = simplCoercionF env co cont
1075
1076 simplExprF1 env (App fun arg) cont
1077 = case arg of
1078 Type ty -> do { -- The argument type will (almost) certainly be used
1079 -- in the output program, so just force it now.
1080 -- See Note [Avoiding space leaks in OutType]
1081 arg' <- simplType env ty
1082
1083 -- But use substTy, not simplType, to avoid forcing
1084 -- the hole type; it will likely not be needed.
1085 -- See Note [The hole type in ApplyToTy]
1086 ; let hole' = substTy env (exprType fun)
1087
1088 ; simplExprF env fun $
1089 ApplyToTy { sc_arg_ty = arg'
1090 , sc_hole_ty = hole'
1091 , sc_cont = cont } }
1092 _ -> simplExprF env fun $
1093 ApplyToVal { sc_arg = arg, sc_env = env
1094 , sc_dup = NoDup, sc_cont = cont }
1095
1096 simplExprF1 env expr@(Lam {}) cont
1097 = simplLam env zapped_bndrs body cont
1098 -- The main issue here is under-saturated lambdas
1099 -- (\x1. \x2. e) arg1
1100 -- Here x1 might have "occurs-once" occ-info, because occ-info
1101 -- is computed assuming that a group of lambdas is applied
1102 -- all at once. If there are too few args, we must zap the
1103 -- occ-info, UNLESS the remaining binders are one-shot
1104 where
1105 (bndrs, body) = collectBinders expr
1106 zapped_bndrs | need_to_zap = map zap bndrs
1107 | otherwise = bndrs
1108
1109 need_to_zap = any zappable_bndr (drop n_args bndrs)
1110 n_args = countArgs cont
1111 -- NB: countArgs counts all the args (incl type args)
1112 -- and likewise drop counts all binders (incl type lambdas)
1113
1114 zappable_bndr b = isId b && not (isOneShotBndr b)
1115 zap b | isTyVar b = b
1116 | otherwise = zapLamIdInfo b
1117
1118 simplExprF1 env (Case scrut bndr _ alts) cont
1119 | sm_case_case (getMode env)
1120 = simplExprF env scrut (Select { sc_dup = NoDup, sc_bndr = bndr
1121 , sc_alts = alts
1122 , sc_env = env, sc_cont = cont })
1123 | otherwise
1124 = do { (env', scrut') <- simplExprF (zapFloats env) scrut $
1125 mkBoringStop (substTy env (idType bndr))
1126 ; let scrut'' = wrapJoinFloats (seJoinFloats env') scrut'
1127 env'' = env `addLetFloats` env'
1128 ; rebuildCase env'' scrut'' bndr alts cont }
1129
1130 simplExprF1 env (Let (Rec pairs) body) cont
1131 = simplRecE env pairs body cont
1132
1133 simplExprF1 env (Let (NonRec bndr rhs) body) cont
1134 | Type ty <- rhs -- First deal with type lets (let a = Type ty in e)
1135 = ASSERT( isTyVar bndr )
1136 do { ty' <- simplType env ty
1137 ; simplExprF (extendTvSubst env bndr ty') body cont }
1138
1139 | otherwise
1140 = simplNonRecE env bndr (rhs, env) ([], body) cont
1141
1142 {- Note [Avoiding space leaks in OutType]
1143 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1144 Since the simplifier is run for multiple iterations, we need to ensure
1145 that any thunks in the output of one simplifier iteration are forced
1146 by the evaluation of the next simplifier iteration. Otherwise we may
1147 retain multiple copies of the Core program and leak a terrible amount
1148 of memory (as in #13426).
1149
1150 The simplifier is naturally strict in the entire "Expr part" of the
1151 input Core program, because any expression may contain binders, which
1152 we must find in order to extend the SimplEnv accordingly. But types
1153 do not contain binders and so it is tempting to write things like
1154
1155 simplExpr env (Type ty) = return (Type (substTy env ty)) -- Bad!
1156
1157 This is Bad because the result includes a thunk (substTy env ty) which
1158 retains a reference to the whole simplifier environment; and the next
1159 simplifier iteration will not force this thunk either, because the
1160 line above is not strict in ty.
1161
1162 So instead our strategy is for the simplifier to fully evaluate
1163 OutTypes when it emits them into the output Core program, for example
1164
1165 simplExpr env (Type ty) = do { ty' <- simplType env ty -- Good
1166 ; return (Type ty') }
1167
1168 where the only difference from above is that simplType calls seqType
1169 on the result of substTy.
1170
1171 However, SimplCont can also contain OutTypes and it's not necessarily
1172 a good idea to force types on the way in to SimplCont, because they
1173 may end up not being used and forcing them could be a lot of wasted
1174 work. T5631 is a good example of this.
1175
1176 - For ApplyToTy's sc_arg_ty, we force the type on the way in because
1177 the type will almost certainly appear as a type argument in the
1178 output program.
1179
1180 - For the hole types in Stop and ApplyToTy, we force the type when we
1181 emit it into the output program, after obtaining it from
1182 contResultType. (The hole type in ApplyToTy is only directly used
1183 to form the result type in a new Stop continuation.)
1184 -}
1185
1186 ---------------------------------
1187 -- Simplify a join point, adding the context.
1188 -- Context goes *inside* the lambdas. IOW, if the join point has arity n, we do:
1189 -- \x1 .. xn -> e => \x1 .. xn -> E[e]
1190 -- Note that we need the arity of the join point, since e may be a lambda
1191 -- (though this is unlikely). See Note [Case-of-case and join points].
1192 simplJoinRhs :: SimplEnv -> InId -> InExpr -> SimplCont
1193 -> SimplM OutExpr
1194 simplJoinRhs env bndr expr cont
1195 | Just arity <- isJoinId_maybe bndr
1196 = do { let (join_bndrs, join_body) = collectNBinders arity expr
1197 ; (env', join_bndrs') <- simplLamBndrs env join_bndrs
1198 ; join_body' <- simplExprC env' join_body cont
1199 ; return $ mkLams join_bndrs' join_body' }
1200
1201 | otherwise
1202 = pprPanic "simplJoinRhs" (ppr bndr)
1203
1204 ---------------------------------
1205 simplType :: SimplEnv -> InType -> SimplM OutType
1206 -- Kept monadic just so we can do the seqType
1207 -- See Note [Avoiding space leaks in OutType]
1208 simplType env ty
1209 = -- pprTrace "simplType" (ppr ty $$ ppr (seTvSubst env)) $
1210 seqType new_ty `seq` return new_ty
1211 where
1212 new_ty = substTy env ty
1213
1214 ---------------------------------
1215 simplCoercionF :: SimplEnv -> InCoercion -> SimplCont
1216 -> SimplM (SimplEnv, OutExpr)
1217 simplCoercionF env co cont
1218 = do { co' <- simplCoercion env co
1219 ; rebuild env (Coercion co') cont }
1220
1221 simplCoercion :: SimplEnv -> InCoercion -> SimplM OutCoercion
1222 simplCoercion env co
1223 = let opt_co = optCoercion (getTCvSubst env) co
1224 in seqCo opt_co `seq` return opt_co
1225
1226 -----------------------------------
1227 -- | Push a TickIt context outwards past applications and cases, as
1228 -- long as this is a non-scoping tick, to let case and application
1229 -- optimisations apply.
1230
1231 simplTick :: SimplEnv -> Tickish Id -> InExpr -> SimplCont
1232 -> SimplM (SimplEnv, OutExpr)
1233 simplTick env tickish expr cont
1234 -- A scoped tick turns into a continuation, so that we can spot
1235 -- (scc t (\x . e)) in simplLam and eliminate the scc. If we didn't do
1236 -- it this way, then it would take two passes of the simplifier to
1237 -- reduce ((scc t (\x . e)) e').
1238 -- NB, don't do this with counting ticks, because if the expr is
1239 -- bottom, then rebuildCall will discard the continuation.
1240
1241 -- XXX: we cannot do this, because the simplifier assumes that
1242 -- the context can be pushed into a case with a single branch. e.g.
1243 -- scc<f> case expensive of p -> e
1244 -- becomes
1245 -- case expensive of p -> scc<f> e
1246 --
1247 -- So I'm disabling this for now. It just means we will do more
1248 -- simplifier iterations that necessary in some cases.
1249
1250 -- | tickishScoped tickish && not (tickishCounts tickish)
1251 -- = simplExprF env expr (TickIt tickish cont)
1252
1253 -- For unscoped or soft-scoped ticks, we are allowed to float in new
1254 -- cost, so we simply push the continuation inside the tick. This
1255 -- has the effect of moving the tick to the outside of a case or
1256 -- application context, allowing the normal case and application
1257 -- optimisations to fire.
1258 | tickish `tickishScopesLike` SoftScope
1259 = do { (env', expr') <- simplExprF env expr cont
1260 ; return (env', mkTick tickish expr')
1261 }
1262
1263 -- Push tick inside if the context looks like this will allow us to
1264 -- do a case-of-case - see Note [case-of-scc-of-case]
1265 | Select {} <- cont, Just expr' <- push_tick_inside
1266 = simplExprF env expr' cont
1267
1268 -- We don't want to move the tick, but we might still want to allow
1269 -- floats to pass through with appropriate wrapping (or not, see
1270 -- wrap_floats below)
1271 --- | not (tickishCounts tickish) || tickishCanSplit tickish
1272 -- = wrap_floats
1273
1274 | otherwise
1275 = no_floating_past_tick
1276
1277 where
1278
1279 -- Try to push tick inside a case, see Note [case-of-scc-of-case].
1280 push_tick_inside =
1281 case expr0 of
1282 Case scrut bndr ty alts
1283 -> Just $ Case (tickScrut scrut) bndr ty (map tickAlt alts)
1284 _other -> Nothing
1285 where (ticks, expr0) = stripTicksTop movable (Tick tickish expr)
1286 movable t = not (tickishCounts t) ||
1287 t `tickishScopesLike` NoScope ||
1288 tickishCanSplit t
1289 tickScrut e = foldr mkTick e ticks
1290 -- Alternatives get annotated with all ticks that scope in some way,
1291 -- but we don't want to count entries.
1292 tickAlt (c,bs,e) = (c,bs, foldr mkTick e ts_scope)
1293 ts_scope = map mkNoCount $
1294 filter (not . (`tickishScopesLike` NoScope)) ticks
1295
1296 no_floating_past_tick =
1297 do { let (inc,outc) = splitCont cont
1298 ; (env1, expr1) <- simplExprF (zapFloats env) expr inc
1299 ; let expr2 = wrapFloats env1 expr1
1300 tickish' = simplTickish env tickish
1301 ; rebuild env (mkTick tickish' expr2) outc
1302 }
1303
1304 -- Alternative version that wraps outgoing floats with the tick. This
1305 -- results in ticks being duplicated, as we don't make any attempt to
1306 -- eliminate the tick if we re-inline the binding (because the tick
1307 -- semantics allows unrestricted inlining of HNFs), so I'm not doing
1308 -- this any more. FloatOut will catch any real opportunities for
1309 -- floating.
1310 --
1311 -- wrap_floats =
1312 -- do { let (inc,outc) = splitCont cont
1313 -- ; (env', expr') <- simplExprF (zapFloats env) expr inc
1314 -- ; let tickish' = simplTickish env tickish
1315 -- ; let wrap_float (b,rhs) = (zapIdStrictness (setIdArity b 0),
1316 -- mkTick (mkNoCount tickish') rhs)
1317 -- -- when wrapping a float with mkTick, we better zap the Id's
1318 -- -- strictness info and arity, because it might be wrong now.
1319 -- ; let env'' = addFloats env (mapFloats env' wrap_float)
1320 -- ; rebuild env'' expr' (TickIt tickish' outc)
1321 -- }
1322
1323
1324 simplTickish env tickish
1325 | Breakpoint n ids <- tickish
1326 = Breakpoint n (map (getDoneId . substId env) ids)
1327 | otherwise = tickish
1328
1329 -- Push type application and coercion inside a tick
1330 splitCont :: SimplCont -> (SimplCont, SimplCont)
1331 splitCont cont@(ApplyToTy { sc_cont = tail }) = (cont { sc_cont = inc }, outc)
1332 where (inc,outc) = splitCont tail
1333 splitCont (CastIt co c) = (CastIt co inc, outc)
1334 where (inc,outc) = splitCont c
1335 splitCont other = (mkBoringStop (contHoleType other), other)
1336
1337 getDoneId (DoneId id) = id
1338 getDoneId (DoneEx e _) = getIdFromTrivialExpr e -- Note [substTickish] in CoreSubst
1339 getDoneId other = pprPanic "getDoneId" (ppr other)
1340
1341 -- Note [case-of-scc-of-case]
1342 -- It's pretty important to be able to transform case-of-case when
1343 -- there's an SCC in the way. For example, the following comes up
1344 -- in nofib/real/compress/Encode.hs:
1345 --
1346 -- case scctick<code_string.r1>
1347 -- case $wcode_string_r13s wild_XC w1_s137 w2_s138 l_aje
1348 -- of _ { (# ww1_s13f, ww2_s13g, ww3_s13h #) ->
1349 -- (ww1_s13f, ww2_s13g, ww3_s13h)
1350 -- }
1351 -- of _ { (ww_s12Y, ww1_s12Z, ww2_s130) ->
1352 -- tick<code_string.f1>
1353 -- (ww_s12Y,
1354 -- ww1_s12Z,
1355 -- PTTrees.PT
1356 -- @ GHC.Types.Char @ GHC.Types.Int wild2_Xj ww2_s130 r_ajf)
1357 -- }
1358 --
1359 -- We really want this case-of-case to fire, because then the 3-tuple
1360 -- will go away (indeed, the CPR optimisation is relying on this
1361 -- happening). But the scctick is in the way - we need to push it
1362 -- inside to expose the case-of-case. So we perform this
1363 -- transformation on the inner case:
1364 --
1365 -- scctick c (case e of { p1 -> e1; ...; pn -> en })
1366 -- ==>
1367 -- case (scctick c e) of { p1 -> scc c e1; ...; pn -> scc c en }
1368 --
1369 -- So we've moved a constant amount of work out of the scc to expose
1370 -- the case. We only do this when the continuation is interesting: in
1371 -- for now, it has to be another Case (maybe generalise this later).
1372
1373 {-
1374 ************************************************************************
1375 * *
1376 \subsection{The main rebuilder}
1377 * *
1378 ************************************************************************
1379 -}
1380
1381 rebuild :: SimplEnv -> OutExpr -> SimplCont -> SimplM (SimplEnv, OutExpr)
1382 -- At this point the substitution in the SimplEnv should be irrelevant
1383 -- only the in-scope set and floats should matter
1384 rebuild env expr cont
1385 = case cont of
1386 Stop {} -> return (env, expr)
1387 TickIt t cont -> rebuild env (mkTick t expr) cont
1388 CastIt co cont -> rebuild env (mkCast expr co) cont
1389 -- NB: mkCast implements the (Coercion co |> g) optimisation
1390
1391 Select { sc_bndr = bndr, sc_alts = alts, sc_env = se, sc_cont = cont }
1392 -> rebuildCase (se `setFloats` env) expr bndr alts cont
1393
1394 StrictArg { sc_fun = fun, sc_cont = cont }
1395 -> rebuildCall env (fun `addValArgTo` expr) cont
1396 StrictBind { sc_bndr = b, sc_bndrs = bs, sc_body = body
1397 , sc_env = se, sc_cont = cont }
1398 -> do { env' <- simplNonRecX (se `setFloats` env) b expr
1399 -- expr satisfies let/app since it started life
1400 -- in a call to simplNonRecE
1401 ; simplLam env' bs body cont }
1402
1403 ApplyToTy { sc_arg_ty = ty, sc_cont = cont}
1404 -> rebuild env (App expr (Type ty)) cont
1405
1406 ApplyToVal { sc_arg = arg, sc_env = se, sc_dup = dup_flag, sc_cont = cont}
1407 -- See Note [Avoid redundant simplification]
1408 -> do { (_, _, arg') <- simplArg env dup_flag se arg
1409 ; rebuild env (App expr arg') cont }
1410
1411 {-
1412 ************************************************************************
1413 * *
1414 \subsection{Lambdas}
1415 * *
1416 ************************************************************************
1417 -}
1418
1419 simplCast :: SimplEnv -> InExpr -> Coercion -> SimplCont
1420 -> SimplM (SimplEnv, OutExpr)
1421 simplCast env body co0 cont0
1422 = do { co1 <- simplCoercion env co0
1423 ; cont1 <- addCoerce co1 cont0
1424 ; simplExprF env body cont1 }
1425 where
1426 addCoerce :: OutCoercion -> SimplCont -> SimplM SimplCont
1427 addCoerce co1 (CastIt co2 cont)
1428 = addCoerce (mkTransCo co1 co2) cont
1429
1430 addCoerce co cont@(ApplyToTy { sc_arg_ty = arg_ty, sc_cont = tail })
1431 | Just (arg_ty', co') <- pushCoTyArg co arg_ty
1432 = do { tail' <- addCoerce co' tail
1433 ; return (cont { sc_arg_ty = arg_ty', sc_cont = tail' }) }
1434
1435 addCoerce co cont@(ApplyToVal { sc_arg = arg, sc_env = arg_se
1436 , sc_dup = dup, sc_cont = tail })
1437 | Just (co1, co2) <- pushCoValArg co
1438 , Pair _ new_ty <- coercionKind co1
1439 , not (isTypeLevPoly new_ty) -- without this check, we get a lev-poly arg
1440 -- See Note [Levity polymorphism invariants] in CoreSyn
1441 -- test: typecheck/should_run/EtaExpandLevPoly
1442 = do { tail' <- addCoerce co2 tail
1443 ; if isReflCo co1
1444 then return (cont { sc_cont = tail' })
1445 -- Avoid simplifying if possible;
1446 -- See Note [Avoiding exponential behaviour]
1447 else do
1448 { (dup', arg_se', arg') <- simplArg env dup arg_se arg
1449 -- When we build the ApplyTo we can't mix the OutCoercion
1450 -- 'co' with the InExpr 'arg', so we simplify
1451 -- to make it all consistent. It's a bit messy.
1452 -- But it isn't a common case.
1453 -- Example of use: Trac #995
1454 ; return (ApplyToVal { sc_arg = mkCast arg' co1
1455 , sc_env = arg_se'
1456 , sc_dup = dup'
1457 , sc_cont = tail' }) } }
1458
1459 addCoerce co cont
1460 | isReflexiveCo co = return cont
1461 | otherwise = return (CastIt co cont)
1462 -- It's worth checking isReflexiveCo.
1463 -- For example, in the initial form of a worker
1464 -- we may find (coerce T (coerce S (\x.e))) y
1465 -- and we'd like it to simplify to e[y/x] in one round
1466 -- of simplification
1467
1468 simplArg :: SimplEnv -> DupFlag -> StaticEnv -> CoreExpr
1469 -> SimplM (DupFlag, StaticEnv, OutExpr)
1470 simplArg env dup_flag arg_env arg
1471 | isSimplified dup_flag
1472 = return (dup_flag, arg_env, arg)
1473 | otherwise
1474 = do { arg' <- simplExpr (arg_env `setInScopeAndZapFloats` env) arg
1475 ; return (Simplified, zapSubstEnv arg_env, arg') }
1476
1477 {-
1478 ************************************************************************
1479 * *
1480 \subsection{Lambdas}
1481 * *
1482 ************************************************************************
1483
1484 Note [Zap unfolding when beta-reducing]
1485 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1486 Lambda-bound variables can have stable unfoldings, such as
1487 $j = \x. \b{Unf=Just x}. e
1488 See Note [Case binders and join points] below; the unfolding for lets
1489 us optimise e better. However when we beta-reduce it we want to
1490 revert to using the actual value, otherwise we can end up in the
1491 stupid situation of
1492 let x = blah in
1493 let b{Unf=Just x} = y
1494 in ...b...
1495 Here it'd be far better to drop the unfolding and use the actual RHS.
1496 -}
1497
1498 simplLam :: SimplEnv -> [InId] -> InExpr -> SimplCont
1499 -> SimplM (SimplEnv, OutExpr)
1500
1501 simplLam env [] body cont = simplExprF env body cont
1502
1503 -- Beta reduction
1504
1505 simplLam env (bndr:bndrs) body (ApplyToTy { sc_arg_ty = arg_ty, sc_cont = cont })
1506 = do { tick (BetaReduction bndr)
1507 ; simplLam (extendTvSubst env bndr arg_ty) bndrs body cont }
1508
1509 simplLam env (bndr:bndrs) body (ApplyToVal { sc_arg = arg, sc_env = arg_se
1510 , sc_cont = cont, sc_dup = dup })
1511 | isSimplified dup -- Don't re-simplify if we've simplified it once
1512 -- See Note [Avoiding exponential behaviour]
1513 = do { tick (BetaReduction bndr)
1514 ; env' <- simplNonRecX env zapped_bndr arg
1515 ; simplLam env' bndrs body cont }
1516
1517 | otherwise
1518 = do { tick (BetaReduction bndr)
1519 ; simplNonRecE env zapped_bndr (arg, arg_se) (bndrs, body) cont }
1520 where
1521 zapped_bndr -- See Note [Zap unfolding when beta-reducing]
1522 | isId bndr, isStableUnfolding (realIdUnfolding bndr)
1523 = setIdUnfolding bndr NoUnfolding
1524 | otherwise = bndr
1525
1526 -- discard a non-counting tick on a lambda. This may change the
1527 -- cost attribution slightly (moving the allocation of the
1528 -- lambda elsewhere), but we don't care: optimisation changes
1529 -- cost attribution all the time.
1530 simplLam env bndrs body (TickIt tickish cont)
1531 | not (tickishCounts tickish)
1532 = simplLam env bndrs body cont
1533
1534 -- Not enough args, so there are real lambdas left to put in the result
1535 simplLam env bndrs body cont
1536 = do { (env', bndrs') <- simplLamBndrs env bndrs
1537 ; body' <- simplExpr env' body
1538 ; new_lam <- mkLam env bndrs' body' cont
1539 ; rebuild env' new_lam cont }
1540
1541 simplLamBndrs :: SimplEnv -> [InBndr] -> SimplM (SimplEnv, [OutBndr])
1542 simplLamBndrs env bndrs = mapAccumLM simplLamBndr env bndrs
1543
1544 -------------
1545 simplLamBndr :: SimplEnv -> InBndr -> SimplM (SimplEnv, OutBndr)
1546 -- Used for lambda binders. These sometimes have unfoldings added by
1547 -- the worker/wrapper pass that must be preserved, because they can't
1548 -- be reconstructed from context. For example:
1549 -- f x = case x of (a,b) -> fw a b x
1550 -- fw a b x{=(a,b)} = ...
1551 -- The "{=(a,b)}" is an unfolding we can't reconstruct otherwise.
1552 simplLamBndr env bndr
1553 | isId bndr && isFragileUnfolding old_unf -- Special case
1554 = do { (env1, bndr1) <- simplBinder env bndr
1555 ; unf' <- simplUnfolding env1 NotTopLevel Nothing bndr old_unf
1556 ; let bndr2 = bndr1 `setIdUnfolding` unf'
1557 ; return (modifyInScope env1 bndr2, bndr2) }
1558
1559 | otherwise
1560 = simplBinder env bndr -- Normal case
1561 where
1562 old_unf = idUnfolding bndr
1563
1564 ------------------
1565 simplNonRecE :: SimplEnv
1566 -> InId -- The binder, always an Id
1567 -- Can be a join point
1568 -> (InExpr, SimplEnv) -- Rhs of binding (or arg of lambda)
1569 -> ([InBndr], InExpr) -- Body of the let/lambda
1570 -- \xs.e
1571 -> SimplCont
1572 -> SimplM (SimplEnv, OutExpr)
1573
1574 -- simplNonRecE is used for
1575 -- * non-top-level non-recursive lets in expressions
1576 -- * beta reduction
1577 --
1578 -- simplNonRec env b (rhs, rhs_se) (bs, body) k
1579 -- = let env in
1580 -- cont< let b = rhs_se(rhs) in \bs.body >
1581 --
1582 -- It deals with strict bindings, via the StrictBind continuation,
1583 -- which may abort the whole process
1584 --
1585 -- Precondition: rhs satisfies the let/app invariant
1586 -- Note [CoreSyn let/app invariant] in CoreSyn
1587 --
1588 -- The "body" of the binding comes as a pair of ([InId],InExpr)
1589 -- representing a lambda; so we recurse back to simplLam
1590 -- Why? Because of the binder-occ-info-zapping done before
1591 -- the call to simplLam in simplExprF (Lam ...)
1592
1593 simplNonRecE env bndr (rhs, rhs_se) (bndrs, body) cont
1594 = ASSERT( isId bndr )
1595 do dflags <- getDynFlags
1596 case () of
1597 _ | preInlineUnconditionally dflags env NotTopLevel bndr rhs
1598 -> do { tick (PreInlineUnconditionally bndr)
1599 ; -- pprTrace "preInlineUncond" (ppr bndr <+> ppr rhs) $
1600 simplLam (extendIdSubst env bndr (mkContEx rhs_se rhs)) bndrs body cont }
1601
1602 -- Deal with join points
1603 | Just (bndr', rhs') <- joinPointBinding_maybe bndr rhs
1604 -> ASSERT( null bndrs ) -- Must be a let-binding;
1605 -- join points are never lambda-bound
1606 do { (env1, cont') <- prepareJoinCont env cont
1607
1608 -- We push cont_dup into the join RHS and the body;
1609 -- and wrap cont_nodup around the whole thing
1610 ; let res_ty = contResultType cont'
1611 ; (env2, bndr1) <- simplNonRecJoinBndr env1 res_ty bndr'
1612 ; (env3, bndr2) <- addBndrRules env2 bndr' bndr1
1613 ; env4 <- simplJoinBind env3 NonRecursive cont'
1614 bndr' bndr2 rhs' rhs_se
1615 ; simplExprF env4 body cont' }
1616
1617 -- Deal with strict bindings
1618 | isStrictId bndr -- Includes coercions
1619 , sm_case_case (getMode env)
1620 -> simplExprF (rhs_se `setFloats` env) rhs
1621 (StrictBind { sc_bndr = bndr, sc_bndrs = bndrs, sc_body = body
1622 , sc_env = env, sc_cont = cont, sc_dup = NoDup })
1623
1624 -- Deal with lazy bindings
1625 | otherwise
1626 -> ASSERT( not (isTyVar bndr) )
1627 do { (env1, bndr1) <- simplNonRecBndr env bndr
1628 ; (env2, bndr2) <- addBndrRules env1 bndr bndr1
1629 ; env3 <- simplLazyBind env2 NotTopLevel NonRecursive bndr bndr2 rhs rhs_se
1630 ; simplLam env3 bndrs body cont }
1631
1632 ------------------
1633 simplRecE :: SimplEnv
1634 -> [(InId, InExpr)]
1635 -> InExpr
1636 -> SimplCont
1637 -> SimplM (SimplEnv, OutExpr)
1638
1639 -- simplRecE is used for
1640 -- * non-top-level recursive lets in expressions
1641 simplRecE env pairs body cont
1642 | Just pairs' <- joinPointBindings_maybe pairs
1643 = do { (env1, cont') <- prepareJoinCont env cont
1644 ; let bndrs' = map fst pairs'
1645 res_ty = contResultType cont
1646 ; env2 <- simplRecJoinBndrs env1 res_ty bndrs'
1647 -- NB: bndrs' don't have unfoldings or rules
1648 -- We add them as we go down
1649 ; env3 <- simplRecBind env2 NotTopLevel (Just cont') pairs'
1650 ; simplExprF env3 body cont' }
1651
1652 | otherwise
1653 = do { let bndrs = map fst pairs
1654 ; MASSERT(all (not . isJoinId) bndrs)
1655 ; env1 <- simplRecBndrs env bndrs
1656 -- NB: bndrs' don't have unfoldings or rules
1657 -- We add them as we go down
1658 ; env2 <- simplRecBind env1 NotTopLevel Nothing pairs
1659 ; simplExprF env2 body cont }
1660
1661 {-
1662 ************************************************************************
1663 * *
1664 Variables
1665 * *
1666 ************************************************************************
1667 -}
1668
1669 simplVar :: SimplEnv -> InVar -> SimplM OutExpr
1670 -- Look up an InVar in the environment
1671 simplVar env var
1672 | isTyVar var = return (Type (substTyVar env var))
1673 | isCoVar var = return (Coercion (substCoVar env var))
1674 | otherwise
1675 = case substId env var of
1676 ContEx tvs cvs ids e -> simplExpr (setSubstEnv env tvs cvs ids) e
1677 DoneId var1 -> return (Var var1)
1678 DoneEx e _ -> return e
1679
1680 simplIdF :: SimplEnv -> InId -> SimplCont -> SimplM (SimplEnv, OutExpr)
1681 simplIdF env var cont
1682 = case substId env var of
1683 ContEx tvs cvs ids e -> simplExprF (setSubstEnv env tvs cvs ids) e cont
1684 -- Don't trim; haven't already simplified e,
1685 -- so the cont is not embodied in e
1686
1687 DoneId var1 -> completeCall env var1 (trim_cont (isJoinId_maybe var1))
1688 DoneEx e mb_join -> simplExprF (zapSubstEnv env) e (trim_cont mb_join)
1689 -- Note [zapSubstEnv]
1690 -- The template is already simplified, so don't re-substitute.
1691 -- This is VITAL. Consider
1692 -- let x = e in
1693 -- let y = \z -> ...x... in
1694 -- \ x -> ...y...
1695 -- We'll clone the inner \x, adding x->x' in the id_subst
1696 -- Then when we inline y, we must *not* replace x by x' in
1697 -- the inlined copy!!
1698 where
1699 trim_cont (Just arity) = trim arity cont
1700 trim_cont Nothing = cont
1701
1702 -- Drop outer context from join point invocation
1703 -- Note [Case-of-case and join points]
1704 trim 0 cont@(Stop {})
1705 = cont
1706 trim 0 cont
1707 = mkBoringStop (contResultType cont)
1708 trim n cont@(ApplyToVal { sc_cont = k })
1709 = cont { sc_cont = trim (n-1) k }
1710 trim n cont@(ApplyToTy { sc_cont = k })
1711 = cont { sc_cont = trim (n-1) k } -- join arity counts types!
1712 trim _ cont
1713 = pprPanic "completeCall" $ ppr var $$ ppr cont
1714
1715 ---------------------------------------------------------
1716 -- Dealing with a call site
1717
1718 completeCall :: SimplEnv -> OutId -> SimplCont -> SimplM (SimplEnv, OutExpr)
1719 completeCall env var cont
1720 = do { ------------- Try inlining ----------------
1721 dflags <- getDynFlags
1722 ; let (lone_variable, arg_infos, call_cont) = contArgs cont
1723 n_val_args = length arg_infos
1724 interesting_cont = interestingCallContext call_cont
1725 unfolding = activeUnfolding env var
1726 maybe_inline = callSiteInline dflags var unfolding
1727 lone_variable arg_infos interesting_cont
1728 ; case maybe_inline of
1729 Just expr -- There is an inlining!
1730 -> do { checkedTick (UnfoldingDone var)
1731 ; dump_inline dflags expr cont
1732 ; simplExprF (zapSubstEnv env) expr cont }
1733
1734 ; Nothing -> do { rule_base <- getSimplRules
1735 ; let info = mkArgInfo var (getRules rule_base var)
1736 n_val_args call_cont
1737 ; rebuildCall env info cont }
1738 }
1739 where
1740 dump_inline dflags unfolding cont
1741 | not (dopt Opt_D_dump_inlinings dflags) = return ()
1742 | not (dopt Opt_D_verbose_core2core dflags)
1743 = when (isExternalName (idName var)) $
1744 liftIO $ printOutputForUser dflags alwaysQualify $
1745 sep [text "Inlining done:", nest 4 (ppr var)]
1746 | otherwise
1747 = liftIO $ printOutputForUser dflags alwaysQualify $
1748 sep [text "Inlining done: " <> ppr var,
1749 nest 4 (vcat [text "Inlined fn: " <+> nest 2 (ppr unfolding),
1750 text "Cont: " <+> ppr cont])]
1751
1752 rebuildCall :: SimplEnv
1753 -> ArgInfo
1754 -> SimplCont
1755 -> SimplM (SimplEnv, OutExpr)
1756 -- We decided not to inline, so
1757 -- - simplify the arguments
1758 -- - try rewrite rules
1759 -- - and rebuild
1760
1761 ---------- Bottoming applications --------------
1762 rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args, ai_strs = [] }) cont
1763 -- When we run out of strictness args, it means
1764 -- that the call is definitely bottom; see SimplUtils.mkArgInfo
1765 -- Then we want to discard the entire strict continuation. E.g.
1766 -- * case (error "hello") of { ... }
1767 -- * (error "Hello") arg
1768 -- * f (error "Hello") where f is strict
1769 -- etc
1770 -- Then, especially in the first of these cases, we'd like to discard
1771 -- the continuation, leaving just the bottoming expression. But the
1772 -- type might not be right, so we may have to add a coerce.
1773 | not (contIsTrivial cont) -- Only do this if there is a non-trivial
1774 -- continuation to discard, else we do it
1775 -- again and again!
1776 = seqType cont_ty `seq` -- See Note [Avoiding space leaks in OutType]
1777 return (env, castBottomExpr res cont_ty)
1778 where
1779 res = argInfoExpr fun rev_args
1780 cont_ty = contResultType cont
1781
1782 ---------- Try rewrite RULES --------------
1783 -- See Note [Trying rewrite rules]
1784 rebuildCall env info@(ArgInfo { ai_fun = fun, ai_args = rev_args
1785 , ai_rules = Just (nr_wanted, rules) }) cont
1786 | nr_wanted == 0 || no_more_args
1787 , let info' = info { ai_rules = Nothing }
1788 = -- We've accumulated a simplified call in <fun,rev_args>
1789 -- so try rewrite rules; see Note [RULEs apply to simplified arguments]
1790 -- See also Note [Rules for recursive functions]
1791 do { mb_match <- tryRules env rules fun (reverse rev_args) cont
1792 ; case mb_match of
1793 Just (env', rhs, cont') -> simplExprF env' rhs cont'
1794 Nothing -> rebuildCall env info' cont }
1795 where
1796 no_more_args = case cont of
1797 ApplyToTy {} -> False
1798 ApplyToVal {} -> False
1799 _ -> True
1800
1801
1802 ---------- Simplify applications and casts --------------
1803 rebuildCall env info (CastIt co cont)
1804 = rebuildCall env (addCastTo info co) cont
1805
1806 rebuildCall env info (ApplyToTy { sc_arg_ty = arg_ty, sc_cont = cont })
1807 = rebuildCall env (addTyArgTo info arg_ty) cont
1808
1809 rebuildCall env info@(ArgInfo { ai_encl = encl_rules, ai_type = fun_ty
1810 , ai_strs = str:strs, ai_discs = disc:discs })
1811 (ApplyToVal { sc_arg = arg, sc_env = arg_se
1812 , sc_dup = dup_flag, sc_cont = cont })
1813 | isSimplified dup_flag -- See Note [Avoid redundant simplification]
1814 = rebuildCall env (addValArgTo info' arg) cont
1815
1816 | str -- Strict argument
1817 , sm_case_case (getMode env)
1818 = -- pprTrace "Strict Arg" (ppr arg $$ ppr (seIdSubst env) $$ ppr (seInScope env)) $
1819 simplExprF (arg_se `setFloats` env) arg
1820 (StrictArg { sc_fun = info', sc_cci = cci_strict
1821 , sc_dup = Simplified, sc_cont = cont })
1822 -- Note [Shadowing]
1823
1824 | otherwise -- Lazy argument
1825 -- DO NOT float anything outside, hence simplExprC
1826 -- There is no benefit (unlike in a let-binding), and we'd
1827 -- have to be very careful about bogus strictness through
1828 -- floating a demanded let.
1829 = do { arg' <- simplExprC (arg_se `setInScopeAndZapFloats` env) arg
1830 (mkLazyArgStop arg_ty cci_lazy)
1831 ; rebuildCall env (addValArgTo info' arg') cont }
1832 where
1833 info' = info { ai_strs = strs, ai_discs = discs }
1834 arg_ty = funArgTy fun_ty
1835
1836 -- Use this for lazy arguments
1837 cci_lazy | encl_rules = RuleArgCtxt
1838 | disc > 0 = DiscArgCtxt -- Be keener here
1839 | otherwise = BoringCtxt -- Nothing interesting
1840
1841 -- ..and this for strict arguments
1842 cci_strict | encl_rules = RuleArgCtxt
1843 | disc > 0 = DiscArgCtxt
1844 | otherwise = RhsCtxt
1845 -- Why RhsCtxt? if we see f (g x) (h x), and f is strict, we
1846 -- want to be a bit more eager to inline g, because it may
1847 -- expose an eval (on x perhaps) that can be eliminated or
1848 -- shared. I saw this in nofib 'boyer2', RewriteFuns.onewayunify1
1849 -- It's worth an 18% improvement in allocation for this
1850 -- particular benchmark; 5% on 'mate' and 1.3% on 'multiplier'
1851
1852 ---------- No further useful info, revert to generic rebuild ------------
1853 rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args }) cont
1854 = rebuild env (argInfoExpr fun rev_args) cont
1855
1856 {- Note [Trying rewrite rules]
1857 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1858 Consider an application (f e1 e2 e3) where the e1,e2,e3 are not yet
1859 simplified. We want to simplify enough arguments to allow the rules
1860 to apply, but it's more efficient to avoid simplifying e2,e3 if e1 alone
1861 is sufficient. Example: class ops
1862 (+) dNumInt e2 e3
1863 If we rewrite ((+) dNumInt) to plusInt, we can take advantage of the
1864 latter's strictness when simplifying e2, e3. Moreover, suppose we have
1865 RULE f Int = \x. x True
1866
1867 Then given (f Int e1) we rewrite to
1868 (\x. x True) e1
1869 without simpifying e1. Now we can inline x into its unique call site,
1870 and absorb the True into it all in the same pass. If we simplified
1871 e1 first, we couldn't do that; see Note [Avoiding exponential behaviour].
1872
1873 So we try to apply rules if either
1874 (a) no_more_args: we've run out of argument that the rules can "see"
1875 (b) nr_wanted: none of the rules wants any more arguments
1876
1877
1878 Note [RULES apply to simplified arguments]
1879 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1880 It's very desirable to try RULES once the arguments have been simplified, because
1881 doing so ensures that rule cascades work in one pass. Consider
1882 {-# RULES g (h x) = k x
1883 f (k x) = x #-}
1884 ...f (g (h x))...
1885 Then we want to rewrite (g (h x)) to (k x) and only then try f's rules. If
1886 we match f's rules against the un-simplified RHS, it won't match. This
1887 makes a particularly big difference when superclass selectors are involved:
1888 op ($p1 ($p2 (df d)))
1889 We want all this to unravel in one sweep.
1890
1891 Note [Avoid redundant simplification]
1892 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1893 Because RULES apply to simplified arguments, there's a danger of repeatedly
1894 simplifying already-simplified arguments. An important example is that of
1895 (>>=) d e1 e2
1896 Here e1, e2 are simplified before the rule is applied, but don't really
1897 participate in the rule firing. So we mark them as Simplified to avoid
1898 re-simplifying them.
1899
1900 Note [Shadowing]
1901 ~~~~~~~~~~~~~~~~
1902 This part of the simplifier may break the no-shadowing invariant
1903 Consider
1904 f (...(\a -> e)...) (case y of (a,b) -> e')
1905 where f is strict in its second arg
1906 If we simplify the innermost one first we get (...(\a -> e)...)
1907 Simplifying the second arg makes us float the case out, so we end up with
1908 case y of (a,b) -> f (...(\a -> e)...) e'
1909 So the output does not have the no-shadowing invariant. However, there is
1910 no danger of getting name-capture, because when the first arg was simplified
1911 we used an in-scope set that at least mentioned all the variables free in its
1912 static environment, and that is enough.
1913
1914 We can't just do innermost first, or we'd end up with a dual problem:
1915 case x of (a,b) -> f e (...(\a -> e')...)
1916
1917 I spent hours trying to recover the no-shadowing invariant, but I just could
1918 not think of an elegant way to do it. The simplifier is already knee-deep in
1919 continuations. We have to keep the right in-scope set around; AND we have
1920 to get the effect that finding (error "foo") in a strict arg position will
1921 discard the entire application and replace it with (error "foo"). Getting
1922 all this at once is TOO HARD!
1923
1924
1925 ************************************************************************
1926 * *
1927 Rewrite rules
1928 * *
1929 ************************************************************************
1930 -}
1931
1932 tryRules :: SimplEnv -> [CoreRule]
1933 -> Id -> [ArgSpec]
1934 -> SimplCont
1935 -> SimplM (Maybe (SimplEnv, CoreExpr, SimplCont))
1936
1937 tryRules env rules fn args call_cont
1938 | null rules
1939 = return Nothing
1940 {- Disabled until we fix #8326
1941 | fn `hasKey` tagToEnumKey -- See Note [Optimising tagToEnum#]
1942 , [_type_arg, val_arg] <- args
1943 , Select dup bndr ((_,[],rhs1) : rest_alts) se cont <- call_cont
1944 , isDeadBinder bndr
1945 = do { dflags <- getDynFlags
1946 ; let enum_to_tag :: CoreAlt -> CoreAlt
1947 -- Takes K -> e into tagK# -> e
1948 -- where tagK# is the tag of constructor K
1949 enum_to_tag (DataAlt con, [], rhs)
1950 = ASSERT( isEnumerationTyCon (dataConTyCon con) )
1951 (LitAlt tag, [], rhs)
1952 where
1953 tag = mkMachInt dflags (toInteger (dataConTag con - fIRST_TAG))
1954 enum_to_tag alt = pprPanic "tryRules: tagToEnum" (ppr alt)
1955
1956 new_alts = (DEFAULT, [], rhs1) : map enum_to_tag rest_alts
1957 new_bndr = setIdType bndr intPrimTy
1958 -- The binder is dead, but should have the right type
1959 ; return (Just (val_arg, Select dup new_bndr new_alts se cont)) }
1960 -}
1961 | otherwise
1962 = do { dflags <- getDynFlags
1963 ; case lookupRule dflags (getUnfoldingInRuleMatch env) (activeRule env)
1964 fn (argInfoAppArgs args) rules of {
1965 Nothing ->
1966 do { nodump dflags -- This ensures that an empty file is written
1967 ; return Nothing } ; -- No rule matches
1968 Just (rule, rule_rhs) ->
1969 do { checkedTick (RuleFired (ruleName rule))
1970 ; let cont' = pushSimplifiedArgs zapped_env
1971 (drop (ruleArity rule) args)
1972 call_cont
1973 -- (ruleArity rule) says how
1974 -- many args the rule consumed
1975
1976 occ_anald_rhs = occurAnalyseExpr rule_rhs
1977 -- See Note [Occurrence-analyse after rule firing]
1978 ; dump dflags rule rule_rhs
1979 ; return (Just (zapped_env, occ_anald_rhs, cont')) }}}
1980 -- The occ_anald_rhs and cont' are all Out things
1981 -- hence zapping the environment
1982 where
1983 zapped_env = zapSubstEnv env -- See Note [zapSubstEnv]
1984
1985 printRuleModule rule =
1986 parens
1987 (maybe (text "BUILTIN") (pprModuleName . moduleName) (ruleModule rule))
1988
1989 dump dflags rule rule_rhs
1990 | dopt Opt_D_dump_rule_rewrites dflags
1991 = log_rule dflags Opt_D_dump_rule_rewrites "Rule fired" $ vcat
1992 [ text "Rule:" <+> ftext (ruleName rule)
1993 , text "Module:" <+> printRuleModule rule
1994 , text "Before:" <+> hang (ppr fn) 2 (sep (map ppr args))
1995 , text "After: " <+> pprCoreExpr rule_rhs
1996 , text "Cont: " <+> ppr call_cont ]
1997
1998 | dopt Opt_D_dump_rule_firings dflags
1999 = log_rule dflags Opt_D_dump_rule_firings "Rule fired:" $
2000 ftext (ruleName rule)
2001 <+> printRuleModule rule
2002
2003 | otherwise
2004 = return ()
2005
2006 nodump dflags
2007 | dopt Opt_D_dump_rule_rewrites dflags
2008 = liftIO $ dumpSDoc dflags alwaysQualify Opt_D_dump_rule_rewrites "" empty
2009
2010 | dopt Opt_D_dump_rule_firings dflags
2011 = liftIO $ dumpSDoc dflags alwaysQualify Opt_D_dump_rule_firings "" empty
2012
2013 | otherwise
2014 = return ()
2015
2016 log_rule dflags flag hdr details
2017 = liftIO . dumpSDoc dflags alwaysQualify flag "" $
2018 sep [text hdr, nest 4 details]
2019
2020 trySeqRules :: SimplEnv
2021 -> OutExpr -> InExpr -- Scrutinee and RHS
2022 -> SimplCont
2023 -> SimplM (Maybe (SimplEnv, CoreExpr, SimplCont))
2024 -- See Note [User-defined RULES for seq]
2025 trySeqRules in_env scrut rhs cont
2026 = do { rule_base <- getSimplRules
2027 ; tryRules in_env (getRules rule_base seqId) seqId out_args rule_cont }
2028 where
2029 no_cast_scrut = drop_casts scrut
2030 scrut_ty = exprType no_cast_scrut
2031 seq_id_ty = idType seqId
2032 rhs_ty = substTy in_env (exprType rhs)
2033 out_args = [ TyArg { as_arg_ty = scrut_ty
2034 , as_hole_ty = seq_id_ty }
2035 , TyArg { as_arg_ty = rhs_ty
2036 , as_hole_ty = piResultTy seq_id_ty scrut_ty }
2037 , ValArg no_cast_scrut]
2038 rule_cont = ApplyToVal { sc_dup = NoDup, sc_arg = rhs
2039 , sc_env = in_env, sc_cont = cont }
2040 -- Lazily evaluated, so we don't do most of this
2041
2042 drop_casts (Cast e _) = drop_casts e
2043 drop_casts e = e
2044
2045 {- Note [User-defined RULES for seq]
2046 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2047 Given
2048 case (scrut |> co) of _ -> rhs
2049 look for rules that match the expression
2050 seq @t1 @t2 scrut
2051 where scrut :: t1
2052 rhs :: t2
2053
2054 If you find a match, rewrite it, and apply to 'rhs'.
2055
2056 Notice that we can simply drop casts on the fly here, which
2057 makes it more likely that a rule will match.
2058
2059 See Note [User-defined RULES for seq] in MkId.
2060
2061 Note [Occurrence-analyse after rule firing]
2062 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2063 After firing a rule, we occurrence-analyse the instantiated RHS before
2064 simplifying it. Usually this doesn't make much difference, but it can
2065 be huge. Here's an example (simplCore/should_compile/T7785)
2066
2067 map f (map f (map f xs)
2068
2069 = -- Use build/fold form of map, twice
2070 map f (build (\cn. foldr (mapFB c f) n
2071 (build (\cn. foldr (mapFB c f) n xs))))
2072
2073 = -- Apply fold/build rule
2074 map f (build (\cn. (\cn. foldr (mapFB c f) n xs) (mapFB c f) n))
2075
2076 = -- Beta-reduce
2077 -- Alas we have no occurrence-analysed, so we don't know
2078 -- that c is used exactly once
2079 map f (build (\cn. let c1 = mapFB c f in
2080 foldr (mapFB c1 f) n xs))
2081
2082 = -- Use mapFB rule: mapFB (mapFB c f) g = mapFB c (f.g)
2083 -- We can do this because (mapFB c n) is a PAP and hence expandable
2084 map f (build (\cn. let c1 = mapFB c n in
2085 foldr (mapFB c (f.f)) n x))
2086
2087 This is not too bad. But now do the same with the outer map, and
2088 we get another use of mapFB, and t can interact with /both/ remaining
2089 mapFB calls in the above expression. This is stupid because actually
2090 that 'c1' binding is dead. The outer map introduces another c2. If
2091 there is a deep stack of maps we get lots of dead bindings, and lots
2092 of redundant work as we repeatedly simplify the result of firing rules.
2093
2094 The easy thing to do is simply to occurrence analyse the result of
2095 the rule firing. Note that this occ-anals not only the RHS of the
2096 rule, but also the function arguments, which by now are OutExprs.
2097 E.g.
2098 RULE f (g x) = x+1
2099
2100 Call f (g BIG) --> (\x. x+1) BIG
2101
2102 The rule binders are lambda-bound and applied to the OutExpr arguments
2103 (here BIG) which lack all internal occurrence info.
2104
2105 Is this inefficient? Not really: we are about to walk over the result
2106 of the rule firing to simplify it, so occurrence analysis is at most
2107 a constant factor.
2108
2109 Possible improvement: occ-anal the rules when putting them in the
2110 database; and in the simplifier just occ-anal the OutExpr arguments.
2111 But that's more complicated and the rule RHS is usually tiny; so I'm
2112 just doing the simple thing.
2113
2114 Historical note: previously we did occ-anal the rules in Rule.hs,
2115 but failed to occ-anal the OutExpr arguments, which led to the
2116 nasty performance problem described above.
2117
2118
2119 Note [Optimising tagToEnum#]
2120 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2121 If we have an enumeration data type:
2122
2123 data Foo = A | B | C
2124
2125 Then we want to transform
2126
2127 case tagToEnum# x of ==> case x of
2128 A -> e1 DEFAULT -> e1
2129 B -> e2 1# -> e2
2130 C -> e3 2# -> e3
2131
2132 thereby getting rid of the tagToEnum# altogether. If there was a DEFAULT
2133 alternative we retain it (remember it comes first). If not the case must
2134 be exhaustive, and we reflect that in the transformed version by adding
2135 a DEFAULT. Otherwise Lint complains that the new case is not exhaustive.
2136 See #8317.
2137
2138 Note [Rules for recursive functions]
2139 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2140 You might think that we shouldn't apply rules for a loop breaker:
2141 doing so might give rise to an infinite loop, because a RULE is
2142 rather like an extra equation for the function:
2143 RULE: f (g x) y = x+y
2144 Eqn: f a y = a-y
2145
2146 But it's too drastic to disable rules for loop breakers.
2147 Even the foldr/build rule would be disabled, because foldr
2148 is recursive, and hence a loop breaker:
2149 foldr k z (build g) = g k z
2150 So it's up to the programmer: rules can cause divergence
2151
2152
2153 ************************************************************************
2154 * *
2155 Rebuilding a case expression
2156 * *
2157 ************************************************************************
2158
2159 Note [Case elimination]
2160 ~~~~~~~~~~~~~~~~~~~~~~~
2161 The case-elimination transformation discards redundant case expressions.
2162 Start with a simple situation:
2163
2164 case x# of ===> let y# = x# in e
2165 y# -> e
2166
2167 (when x#, y# are of primitive type, of course). We can't (in general)
2168 do this for algebraic cases, because we might turn bottom into
2169 non-bottom!
2170
2171 The code in SimplUtils.prepareAlts has the effect of generalise this
2172 idea to look for a case where we're scrutinising a variable, and we
2173 know that only the default case can match. For example:
2174
2175 case x of
2176 0# -> ...
2177 DEFAULT -> ...(case x of
2178 0# -> ...
2179 DEFAULT -> ...) ...
2180
2181 Here the inner case is first trimmed to have only one alternative, the
2182 DEFAULT, after which it's an instance of the previous case. This
2183 really only shows up in eliminating error-checking code.
2184
2185 Note that SimplUtils.mkCase combines identical RHSs. So
2186
2187 case e of ===> case e of DEFAULT -> r
2188 True -> r
2189 False -> r
2190
2191 Now again the case may be elminated by the CaseElim transformation.
2192 This includes things like (==# a# b#)::Bool so that we simplify
2193 case ==# a# b# of { True -> x; False -> x }
2194 to just
2195 x
2196 This particular example shows up in default methods for
2197 comparison operations (e.g. in (>=) for Int.Int32)
2198
2199 Note [Case elimination: lifted case]
2200 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2201 If a case over a lifted type has a single alternative, and is being used
2202 as a strict 'let' (all isDeadBinder bndrs), we may want to do this
2203 transformation:
2204
2205 case e of r ===> let r = e in ...r...
2206 _ -> ...r...
2207
2208 (a) 'e' is already evaluated (it may so if e is a variable)
2209 Specifically we check (exprIsHNF e). In this case
2210 we can just allocate the WHNF directly with a let.
2211 or
2212 (b) 'x' is not used at all and e is ok-for-speculation
2213 The ok-for-spec bit checks that we don't lose any
2214 exceptions or divergence.
2215
2216 NB: it'd be *sound* to switch from case to let if the
2217 scrutinee was not yet WHNF but was guaranteed to
2218 converge; but sticking with case means we won't build a
2219 thunk
2220
2221 or
2222 (c) 'x' is used strictly in the body, and 'e' is a variable
2223 Then we can just substitute 'e' for 'x' in the body.
2224 See Note [Eliminating redundant seqs]
2225
2226 For (b), the "not used at all" test is important. Consider
2227 case (case a ># b of { True -> (p,q); False -> (q,p) }) of
2228 r -> blah
2229 The scrutinee is ok-for-speculation (it looks inside cases), but we do
2230 not want to transform to
2231 let r = case a ># b of { True -> (p,q); False -> (q,p) }
2232 in blah
2233 because that builds an unnecessary thunk.
2234
2235 Note [Eliminating redundant seqs]
2236 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2237 If we have this:
2238 case x of r { _ -> ..r.. }
2239 where 'r' is used strictly in (..r..), the case is effectively a 'seq'
2240 on 'x', but since 'r' is used strictly anyway, we can safely transform to
2241 (...x...)
2242
2243 Note that this can change the error behaviour. For example, we might
2244 transform
2245 case x of { _ -> error "bad" }
2246 --> error "bad"
2247 which is might be puzzling if 'x' currently lambda-bound, but later gets
2248 let-bound to (error "good").
2249
2250 Nevertheless, the paper "A semantics for imprecise exceptions" allows
2251 this transformation. If you want to fix the evaluation order, use
2252 'pseq'. See Trac #8900 for an example where the loss of this
2253 transformation bit us in practice.
2254
2255 See also Note [Empty case alternatives] in CoreSyn.
2256
2257 Just for reference, the original code (added Jan 13) looked like this:
2258 || case_bndr_evald_next rhs
2259
2260 case_bndr_evald_next :: CoreExpr -> Bool
2261 -- See Note [Case binder next]
2262 case_bndr_evald_next (Var v) = v == case_bndr
2263 case_bndr_evald_next (Cast e _) = case_bndr_evald_next e
2264 case_bndr_evald_next (App e _) = case_bndr_evald_next e
2265 case_bndr_evald_next (Case e _ _ _) = case_bndr_evald_next e
2266 case_bndr_evald_next _ = False
2267
2268 (This came up when fixing Trac #7542. See also Note [Eta reduction of
2269 an eval'd function] in CoreUtils.)
2270
2271
2272 Note [Case elimination: unlifted case]
2273 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2274 Consider
2275 case a +# b of r -> ...r...
2276 Then we do case-elimination (to make a let) followed by inlining,
2277 to get
2278 .....(a +# b)....
2279 If we have
2280 case indexArray# a i of r -> ...r...
2281 we might like to do the same, and inline the (indexArray# a i).
2282 But indexArray# is not okForSpeculation, so we don't build a let
2283 in rebuildCase (lest it get floated *out*), so the inlining doesn't
2284 happen either.
2285
2286 This really isn't a big deal I think. The let can be
2287
2288
2289 Further notes about case elimination
2290 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2291 Consider: test :: Integer -> IO ()
2292 test = print
2293
2294 Turns out that this compiles to:
2295 Print.test
2296 = \ eta :: Integer
2297 eta1 :: Void# ->
2298 case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT ->
2299 case hPutStr stdout
2300 (PrelNum.jtos eta ($w[] @ Char))
2301 eta1
2302 of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s }}
2303
2304 Notice the strange '<' which has no effect at all. This is a funny one.
2305 It started like this:
2306
2307 f x y = if x < 0 then jtos x
2308 else if y==0 then "" else jtos x
2309
2310 At a particular call site we have (f v 1). So we inline to get
2311
2312 if v < 0 then jtos x
2313 else if 1==0 then "" else jtos x
2314
2315 Now simplify the 1==0 conditional:
2316
2317 if v<0 then jtos v else jtos v
2318
2319 Now common-up the two branches of the case:
2320
2321 case (v<0) of DEFAULT -> jtos v
2322
2323 Why don't we drop the case? Because it's strict in v. It's technically
2324 wrong to drop even unnecessary evaluations, and in practice they
2325 may be a result of 'seq' so we *definitely* don't want to drop those.
2326 I don't really know how to improve this situation.
2327 -}
2328
2329 ---------------------------------------------------------
2330 -- Eliminate the case if possible
2331
2332 rebuildCase, reallyRebuildCase
2333 :: SimplEnv
2334 -> OutExpr -- Scrutinee
2335 -> InId -- Case binder
2336 -> [InAlt] -- Alternatives (inceasing order)
2337 -> SimplCont
2338 -> SimplM (SimplEnv, OutExpr)
2339
2340 --------------------------------------------------
2341 -- 1. Eliminate the case if there's a known constructor
2342 --------------------------------------------------
2343
2344 rebuildCase env scrut case_bndr alts cont
2345 | Lit lit <- scrut -- No need for same treatment as constructors
2346 -- because literals are inlined more vigorously
2347 , not (litIsLifted lit)
2348 = do { tick (KnownBranch case_bndr)
2349 ; case findAlt (LitAlt lit) alts of
2350 Nothing -> missingAlt env case_bndr alts cont
2351 Just (_, bs, rhs) -> simple_rhs bs rhs }
2352
2353 | Just (con, ty_args, other_args) <- exprIsConApp_maybe (getUnfoldingInRuleMatch env) scrut
2354 -- Works when the scrutinee is a variable with a known unfolding
2355 -- as well as when it's an explicit constructor application
2356 = do { tick (KnownBranch case_bndr)
2357 ; case findAlt (DataAlt con) alts of
2358 Nothing -> missingAlt env case_bndr alts cont
2359 Just (DEFAULT, bs, rhs) -> simple_rhs bs rhs
2360 Just (_, bs, rhs) -> knownCon env scrut con ty_args other_args
2361 case_bndr bs rhs cont
2362 }
2363 where
2364 simple_rhs bs rhs = ASSERT( null bs )
2365 do { env' <- simplNonRecX env case_bndr scrut
2366 -- scrut is a constructor application,
2367 -- hence satisfies let/app invariant
2368 ; simplExprF env' rhs cont }
2369
2370
2371 --------------------------------------------------
2372 -- 2. Eliminate the case if scrutinee is evaluated
2373 --------------------------------------------------
2374
2375 rebuildCase env scrut case_bndr alts@[(_, bndrs, rhs)] cont
2376 -- See if we can get rid of the case altogether
2377 -- See Note [Case elimination]
2378 -- mkCase made sure that if all the alternatives are equal,
2379 -- then there is now only one (DEFAULT) rhs
2380
2381 -- 2a. Dropping the case altogether, if
2382 -- a) it binds nothing (so it's really just a 'seq')
2383 -- b) evaluating the scrutinee has no side effects
2384 | is_plain_seq
2385 , exprOkForSideEffects scrut
2386 -- The entire case is dead, so we can drop it
2387 -- if the scrutinee converges without having imperative
2388 -- side effects or raising a Haskell exception
2389 -- See Note [PrimOp can_fail and has_side_effects] in PrimOp
2390 = simplExprF env rhs cont
2391
2392 -- 2b. Turn the case into a let, if
2393 -- a) it binds only the case-binder
2394 -- b) unlifted case: the scrutinee is ok-for-speculation
2395 -- lifted case: the scrutinee is in HNF (or will later be demanded)
2396 | all_dead_bndrs
2397 , if is_unlifted
2398 then exprOkForSpeculation scrut -- See Note [Case elimination: unlifted case]
2399 else exprIsHNF scrut -- See Note [Case elimination: lifted case]
2400 || scrut_is_demanded_var scrut
2401 = do { tick (CaseElim case_bndr)
2402 ; env' <- simplNonRecX env case_bndr scrut
2403 ; simplExprF env' rhs cont }
2404
2405 -- 2c. Try the seq rules if
2406 -- a) it binds only the case binder
2407 -- b) a rule for seq applies
2408 -- See Note [User-defined RULES for seq] in MkId
2409 | is_plain_seq
2410 = do { mb_rule <- trySeqRules env scrut rhs cont
2411 ; case mb_rule of
2412 Just (env', rule_rhs, cont') -> simplExprF env' rule_rhs cont'
2413 Nothing -> reallyRebuildCase env scrut case_bndr alts cont }
2414 where
2415 is_unlifted = isUnliftedType (idType case_bndr)
2416 all_dead_bndrs = all isDeadBinder bndrs -- bndrs are [InId]
2417 is_plain_seq = all_dead_bndrs && isDeadBinder case_bndr -- Evaluation *only* for effect
2418
2419 scrut_is_demanded_var :: CoreExpr -> Bool
2420 -- See Note [Eliminating redundant seqs]
2421 scrut_is_demanded_var (Cast s _) = scrut_is_demanded_var s
2422 scrut_is_demanded_var (Var _) = isStrictDmd (idDemandInfo case_bndr)
2423 scrut_is_demanded_var _ = False
2424
2425
2426 rebuildCase env scrut case_bndr alts cont
2427 = reallyRebuildCase env scrut case_bndr alts cont
2428
2429 --------------------------------------------------
2430 -- 3. Catch-all case
2431 --------------------------------------------------
2432
2433 reallyRebuildCase env scrut case_bndr alts cont
2434 = do { -- Prepare the continuation;
2435 -- The new subst_env is in place
2436 (env, alt_cont, wrap_cont) <- prepareCaseCont env alts cont
2437
2438 -- Simplify the alternatives
2439 ; (scrut', case_bndr', alts') <- simplAlts env scrut case_bndr alts alt_cont
2440
2441 ; dflags <- getDynFlags
2442 ; let alts_ty' = contResultType alt_cont
2443 -- See Note [Avoiding space leaks in OutType]
2444 ; case_expr <- seqType alts_ty' `seq`
2445 mkCase dflags scrut' case_bndr' alts_ty' alts'
2446
2447 -- Notice that rebuild gets the in-scope set from env', not alt_env
2448 -- (which in any case is only build in simplAlts)
2449 -- The case binder *not* scope over the whole returned case-expression
2450 ; rebuild env case_expr wrap_cont }
2451
2452 {-
2453 simplCaseBinder checks whether the scrutinee is a variable, v. If so,
2454 try to eliminate uses of v in the RHSs in favour of case_bndr; that
2455 way, there's a chance that v will now only be used once, and hence
2456 inlined.
2457
2458 Historical note: we use to do the "case binder swap" in the Simplifier
2459 so there were additional complications if the scrutinee was a variable.
2460 Now the binder-swap stuff is done in the occurrence analyser; see
2461 OccurAnal Note [Binder swap].
2462
2463 Note [knownCon occ info]
2464 ~~~~~~~~~~~~~~~~~~~~~~~~
2465 If the case binder is not dead, then neither are the pattern bound
2466 variables:
2467 case <any> of x { (a,b) ->
2468 case x of { (p,q) -> p } }
2469 Here (a,b) both look dead, but come alive after the inner case is eliminated.
2470 The point is that we bring into the envt a binding
2471 let x = (a,b)
2472 after the outer case, and that makes (a,b) alive. At least we do unless
2473 the case binder is guaranteed dead.
2474
2475 Note [Case alternative occ info]
2476 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2477 When we are simply reconstructing a case (the common case), we always
2478 zap the occurrence info on the binders in the alternatives. Even
2479 if the case binder is dead, the scrutinee is usually a variable, and *that*
2480 can bring the case-alternative binders back to life.
2481 See Note [Add unfolding for scrutinee]
2482
2483 Note [Improving seq]
2484 ~~~~~~~~~~~~~~~~~~~
2485 Consider
2486 type family F :: * -> *
2487 type instance F Int = Int
2488
2489 We'd like to transform
2490 case e of (x :: F Int) { DEFAULT -> rhs }
2491 ===>
2492 case e `cast` co of (x'::Int)
2493 I# x# -> let x = x' `cast` sym co
2494 in rhs
2495
2496 so that 'rhs' can take advantage of the form of x'. Notice that Note
2497 [Case of cast] (in OccurAnal) may then apply to the result.
2498
2499 We'd also like to eliminate empty types (Trac #13468). So if
2500
2501 data Void
2502 type instance F Bool = Void
2503
2504 then we'd like to transform
2505 case (x :: F Bool) of { _ -> error "urk" }
2506 ===>
2507 case (x |> co) of (x' :: Void) of {}
2508
2509 Nota Bene: we used to have a built-in rule for 'seq' that dropped
2510 casts, so that
2511 case (x |> co) of { _ -> blah }
2512 dropped the cast; in order to improve the chances of trySeqRules
2513 firing. But that works in the /opposite/ direction to Note [Improving
2514 seq] so there's a danger of flip/flopping. Better to make trySeqRules
2515 insensitive to the cast, which is now is.
2516
2517 The need for [Improving seq] showed up in Roman's experiments. Example:
2518 foo :: F Int -> Int -> Int
2519 foo t n = t `seq` bar n
2520 where
2521 bar 0 = 0
2522 bar n = bar (n - case t of TI i -> i)
2523 Here we'd like to avoid repeated evaluating t inside the loop, by
2524 taking advantage of the `seq`.
2525
2526 At one point I did transformation in LiberateCase, but it's more
2527 robust here. (Otherwise, there's a danger that we'll simply drop the
2528 'seq' altogether, before LiberateCase gets to see it.)
2529 -}
2530
2531 simplAlts :: SimplEnv
2532 -> OutExpr
2533 -> InId -- Case binder
2534 -> [InAlt] -- Non-empty
2535 -> SimplCont
2536 -> SimplM (OutExpr, OutId, [OutAlt]) -- Includes the continuation
2537 -- Like simplExpr, this just returns the simplified alternatives;
2538 -- it does not return an environment
2539 -- The returned alternatives can be empty, none are possible
2540
2541 simplAlts env scrut case_bndr alts cont'
2542 = do { let env0 = zapFloats env
2543
2544 ; (env1, case_bndr1) <- simplBinder env0 case_bndr
2545 ; let case_bndr2 = case_bndr1 `setIdUnfolding` evaldUnfolding
2546 env2 = modifyInScope env1 case_bndr2
2547 -- See Note [Case binder evaluated-ness]
2548
2549 ; fam_envs <- getFamEnvs
2550 ; (alt_env', scrut', case_bndr') <- improveSeq fam_envs env2 scrut
2551 case_bndr case_bndr2 alts
2552
2553 ; (imposs_deflt_cons, in_alts) <- prepareAlts scrut' case_bndr' alts
2554 -- NB: it's possible that the returned in_alts is empty: this is handled
2555 -- by the caller (rebuildCase) in the missingAlt function
2556
2557 ; alts' <- mapM (simplAlt alt_env' (Just scrut') imposs_deflt_cons case_bndr' cont') in_alts
2558 ; -- pprTrace "simplAlts" (ppr case_bndr $$ ppr alts_ty $$ ppr alts_ty' $$ ppr alts $$ ppr cont') $
2559 return (scrut', case_bndr', alts') }
2560
2561
2562 ------------------------------------
2563 improveSeq :: (FamInstEnv, FamInstEnv) -> SimplEnv
2564 -> OutExpr -> InId -> OutId -> [InAlt]
2565 -> SimplM (SimplEnv, OutExpr, OutId)
2566 -- Note [Improving seq]
2567 improveSeq fam_envs env scrut case_bndr case_bndr1 [(DEFAULT,_,_)]
2568 | Just (co, ty2) <- topNormaliseType_maybe fam_envs (idType case_bndr1)
2569 = do { case_bndr2 <- newId (fsLit "nt") ty2
2570 ; let rhs = DoneEx (Var case_bndr2 `Cast` mkSymCo co) Nothing
2571 env2 = extendIdSubst env case_bndr rhs
2572 ; return (env2, scrut `Cast` co, case_bndr2) }
2573
2574 improveSeq _ env scrut _ case_bndr1 _
2575 = return (env, scrut, case_bndr1)
2576
2577
2578 ------------------------------------
2579 simplAlt :: SimplEnv
2580 -> Maybe OutExpr -- The scrutinee
2581 -> [AltCon] -- These constructors can't be present when
2582 -- matching the DEFAULT alternative
2583 -> OutId -- The case binder
2584 -> SimplCont
2585 -> InAlt
2586 -> SimplM OutAlt
2587
2588 simplAlt env _ imposs_deflt_cons case_bndr' cont' (DEFAULT, bndrs, rhs)
2589 = ASSERT( null bndrs )
2590 do { let env' = addBinderUnfolding env case_bndr'
2591 (mkOtherCon imposs_deflt_cons)
2592 -- Record the constructors that the case-binder *can't* be.
2593 ; rhs' <- simplExprC env' rhs cont'
2594 ; return (DEFAULT, [], rhs') }
2595
2596 simplAlt env scrut' _ case_bndr' cont' (LitAlt lit, bndrs, rhs)
2597 = ASSERT( null bndrs )
2598 do { env' <- addAltUnfoldings env scrut' case_bndr' (Lit lit)
2599 ; rhs' <- simplExprC env' rhs cont'
2600 ; return (LitAlt lit, [], rhs') }
2601
2602 simplAlt env scrut' _ case_bndr' cont' (DataAlt con, vs, rhs)
2603 = do { -- Deal with the pattern-bound variables
2604 -- Mark the ones that are in ! positions in the
2605 -- data constructor as certainly-evaluated.
2606 -- NB: simplLamBinders preserves this eval info
2607 ; let vs_with_evals = add_evals (dataConRepStrictness con)
2608 ; (env', vs') <- simplLamBndrs env vs_with_evals
2609
2610 -- Bind the case-binder to (con args)
2611 ; let inst_tys' = tyConAppArgs (idType case_bndr')
2612 con_app :: OutExpr
2613 con_app = mkConApp2 con inst_tys' vs'
2614
2615 ; env'' <- addAltUnfoldings env' scrut' case_bndr' con_app
2616 ; rhs' <- simplExprC env'' rhs cont'
2617 ; return (DataAlt con, vs', rhs') }
2618 where
2619 -- add_evals records the evaluated-ness of the bound variables of
2620 -- a case pattern. This is *important*. Consider
2621 -- data T = T !Int !Int
2622 --
2623 -- case x of { T a b -> T (a+1) b }
2624 --
2625 -- We really must record that b is already evaluated so that we don't
2626 -- go and re-evaluate it when constructing the result.
2627 -- See Note [Data-con worker strictness] in MkId.hs
2628 add_evals the_strs
2629 = go vs the_strs
2630 where
2631 go [] [] = []
2632 go (v:vs') strs | isTyVar v = v : go vs' strs
2633 go (v:vs') (str:strs) = zap str v : go vs' strs
2634 go _ _ = pprPanic "cat_evals"
2635 (ppr con $$
2636 ppr vs $$
2637 ppr_with_length the_strs $$
2638 ppr_with_length (dataConRepArgTys con) $$
2639 ppr_with_length (dataConRepStrictness con))
2640 where
2641 ppr_with_length list
2642 = ppr list <+> parens (text "length =" <+> ppr (length list))
2643 -- NB: If this panic triggers, note that
2644 -- NoStrictnessMark doesn't print!
2645
2646 zap str v = setCaseBndrEvald str $ -- Add eval'dness info
2647 zapIdOccInfo v -- And kill occ info;
2648 -- see Note [Case alternative occ info]
2649
2650 addAltUnfoldings :: SimplEnv -> Maybe OutExpr -> OutId -> OutExpr -> SimplM SimplEnv
2651 addAltUnfoldings env scrut case_bndr con_app
2652 = do { dflags <- getDynFlags
2653 ; let con_app_unf = mkSimpleUnfolding dflags con_app
2654 env1 = addBinderUnfolding env case_bndr con_app_unf
2655
2656 -- See Note [Add unfolding for scrutinee]
2657 env2 = case scrut of
2658 Just (Var v) -> addBinderUnfolding env1 v con_app_unf
2659 Just (Cast (Var v) co) -> addBinderUnfolding env1 v $
2660 mkSimpleUnfolding dflags (Cast con_app (mkSymCo co))
2661 _ -> env1
2662
2663 ; traceSmpl "addAltUnf" (vcat [ppr case_bndr <+> ppr scrut, ppr con_app])
2664 ; return env2 }
2665
2666 addBinderUnfolding :: SimplEnv -> Id -> Unfolding -> SimplEnv
2667 addBinderUnfolding env bndr unf
2668 | debugIsOn, Just tmpl <- maybeUnfoldingTemplate unf
2669 = WARN( not (eqType (idType bndr) (exprType tmpl)),
2670 ppr bndr $$ ppr (idType bndr) $$ ppr tmpl $$ ppr (exprType tmpl) )
2671 modifyInScope env (bndr `setIdUnfolding` unf)
2672
2673 | otherwise
2674 = modifyInScope env (bndr `setIdUnfolding` unf)
2675
2676 zapBndrOccInfo :: Bool -> Id -> Id
2677 -- Consider case e of b { (a,b) -> ... }
2678 -- Then if we bind b to (a,b) in "...", and b is not dead,
2679 -- then we must zap the deadness info on a,b
2680 zapBndrOccInfo keep_occ_info pat_id
2681 | keep_occ_info = pat_id
2682 | otherwise = zapIdOccInfo pat_id
2683
2684 {- Note [Case binder evaluated-ness]
2685 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2686 We pin on a (OtherCon []) unfolding to the case-binder of a Case,
2687 even though it'll be over-ridden in every case alternative with a more
2688 informative unfolding. Why? Because suppose a later, less clever, pass
2689 simply replaces all occurrences of the case binder with the binder itself;
2690 then Lint may complain about the let/app invariant. Example
2691 case e of b { DEFAULT -> let v = reallyUnsafePtrEq# b y in ....
2692 ; K -> blah }
2693
2694 The let/app invariant requires that y is evaluated in the call to
2695 reallyUnsafePtrEq#, which it is. But we still want that to be true if we
2696 propagate binders to occurrences.
2697
2698 This showed up in Trac #13027.
2699
2700 Note [Add unfolding for scrutinee]
2701 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2702 In general it's unlikely that a variable scrutinee will appear
2703 in the case alternatives case x of { ...x unlikely to appear... }
2704 because the binder-swap in OccAnal has got rid of all such occcurrences
2705 See Note [Binder swap] in OccAnal.
2706
2707 BUT it is still VERY IMPORTANT to add a suitable unfolding for a
2708 variable scrutinee, in simplAlt. Here's why
2709 case x of y
2710 (a,b) -> case b of c
2711 I# v -> ...(f y)...
2712 There is no occurrence of 'b' in the (...(f y)...). But y gets
2713 the unfolding (a,b), and *that* mentions b. If f has a RULE
2714 RULE f (p, I# q) = ...
2715 we want that rule to match, so we must extend the in-scope env with a
2716 suitable unfolding for 'y'. It's *essential* for rule matching; but
2717 it's also good for case-elimintation -- suppose that 'f' was inlined
2718 and did multi-level case analysis, then we'd solve it in one
2719 simplifier sweep instead of two.
2720
2721 Exactly the same issue arises in SpecConstr;
2722 see Note [Add scrutinee to ValueEnv too] in SpecConstr
2723
2724 HOWEVER, given
2725 case x of y { Just a -> r1; Nothing -> r2 }
2726 we do not want to add the unfolding x -> y to 'x', which might seem cool,
2727 since 'y' itself has different unfoldings in r1 and r2. Reason: if we
2728 did that, we'd have to zap y's deadness info and that is a very useful
2729 piece of information.
2730
2731 So instead we add the unfolding x -> Just a, and x -> Nothing in the
2732 respective RHSs.
2733
2734
2735 ************************************************************************
2736 * *
2737 \subsection{Known constructor}
2738 * *
2739 ************************************************************************
2740
2741 We are a bit careful with occurrence info. Here's an example
2742
2743 (\x* -> case x of (a*, b) -> f a) (h v, e)
2744
2745 where the * means "occurs once". This effectively becomes
2746 case (h v, e) of (a*, b) -> f a)
2747 and then
2748 let a* = h v; b = e in f a
2749 and then
2750 f (h v)
2751
2752 All this should happen in one sweep.
2753 -}
2754
2755 knownCon :: SimplEnv
2756 -> OutExpr -- The scrutinee
2757 -> DataCon -> [OutType] -> [OutExpr] -- The scrutinee (in pieces)
2758 -> InId -> [InBndr] -> InExpr -- The alternative
2759 -> SimplCont
2760 -> SimplM (SimplEnv, OutExpr)
2761
2762 knownCon env scrut dc dc_ty_args dc_args bndr bs rhs cont
2763 = do { env' <- bind_args env bs dc_args
2764 ; env'' <- bind_case_bndr env'
2765 ; simplExprF env'' rhs cont }
2766 where
2767 zap_occ = zapBndrOccInfo (isDeadBinder bndr) -- bndr is an InId
2768
2769 -- Ugh!
2770 bind_args env' [] _ = return env'
2771
2772 bind_args env' (b:bs') (Type ty : args)
2773 = ASSERT( isTyVar b )
2774 bind_args (extendTvSubst env' b ty) bs' args
2775
2776 bind_args env' (b:bs') (Coercion co : args)
2777 = ASSERT( isCoVar b )
2778 bind_args (extendCvSubst env' b co) bs' args
2779
2780 bind_args env' (b:bs') (arg : args)
2781 = ASSERT( isId b )
2782 do { let b' = zap_occ b
2783 -- Note that the binder might be "dead", because it doesn't
2784 -- occur in the RHS; and simplNonRecX may therefore discard
2785 -- it via postInlineUnconditionally.
2786 -- Nevertheless we must keep it if the case-binder is alive,
2787 -- because it may be used in the con_app. See Note [knownCon occ info]
2788 ; env'' <- simplNonRecX env' b' arg -- arg satisfies let/app invariant
2789 ; bind_args env'' bs' args }
2790
2791 bind_args _ _ _ =
2792 pprPanic "bind_args" $ ppr dc $$ ppr bs $$ ppr dc_args $$
2793 text "scrut:" <+> ppr scrut
2794
2795 -- It's useful to bind bndr to scrut, rather than to a fresh
2796 -- binding x = Con arg1 .. argn
2797 -- because very often the scrut is a variable, so we avoid
2798 -- creating, and then subsequently eliminating, a let-binding
2799 -- BUT, if scrut is a not a variable, we must be careful
2800 -- about duplicating the arg redexes; in that case, make
2801 -- a new con-app from the args
2802 bind_case_bndr env
2803 | isDeadBinder bndr = return env
2804 | exprIsTrivial scrut = return (extendIdSubst env bndr (DoneEx scrut Nothing))
2805 | otherwise = do { dc_args <- mapM (simplVar env) bs
2806 -- dc_ty_args are aready OutTypes,
2807 -- but bs are InBndrs
2808 ; let con_app = Var (dataConWorkId dc)
2809 `mkTyApps` dc_ty_args
2810 `mkApps` dc_args
2811 ; simplNonRecX env bndr con_app }
2812
2813 -------------------
2814 missingAlt :: SimplEnv -> Id -> [InAlt] -> SimplCont -> SimplM (SimplEnv, OutExpr)
2815 -- This isn't strictly an error, although it is unusual.
2816 -- It's possible that the simplifier might "see" that
2817 -- an inner case has no accessible alternatives before
2818 -- it "sees" that the entire branch of an outer case is
2819 -- inaccessible. So we simply put an error case here instead.
2820 missingAlt env case_bndr _ cont
2821 = WARN( True, text "missingAlt" <+> ppr case_bndr )
2822 -- See Note [Avoiding space leaks in OutType]
2823 let cont_ty = contResultType cont
2824 in seqType cont_ty `seq` return (env, mkImpossibleExpr cont_ty)
2825
2826 {-
2827 ************************************************************************
2828 * *
2829 \subsection{Duplicating continuations}
2830 * *
2831 ************************************************************************
2832
2833 Consider
2834 let x* = case e of { True -> e1; False -> e2 }
2835 in b
2836 where x* is a strict binding. Then mkDupableCont will be given
2837 the continuation
2838 case [] of { True -> e1; False -> e2 } ; let x* = [] in b ; stop
2839 and will split it into
2840 dupable: case [] of { True -> $j1; False -> $j2 } ; stop
2841 join floats: $j1 = e1, $j2 = e2
2842 non_dupable: let x* = [] in b; stop
2843
2844 Putting this back togeher would give
2845 let x* = let { $j1 = e1; $j2 = e2 } in
2846 case e of { True -> $j1; False -> $j2 }
2847 in b
2848 (Of course we only do this if 'e' wants to duplicate that continuation.)
2849 Note how important it is that the new join points wrap around the
2850 inner expression, and not around the whole thing.
2851
2852 In contrast, any let-bindings introduced by mkDupableCont can wrap
2853 around the entire thing.
2854 -}
2855
2856
2857 prepareCaseCont :: SimplEnv -> [InAlt] -> SimplCont
2858 -> SimplM (SimplEnv,
2859 SimplCont, -- For the alternatives
2860 SimplCont) -- Wraps the entire case
2861 -- We are considering
2862 -- K[ case _ of { p1 -> r1; ...; pn -> rn } ]
2863 -- where K is some enclosing continuation for the case
2864 -- Goal: split K into two pieces Kdup,Knodup so that
2865 -- a) Kdup can be duplicated
2866 -- b) Knodup[Kdup[e]] = K[e]
2867 -- The idea is that we'll transform thus:
2868 -- Knodup[ (case _ of { p1 -> Kdup[r1]; ...; pn -> Kdup[rn] }
2869 --
2870 -- We may also return some extra value bindings in SimplEnv (that scope over
2871 -- the entire continuation) as well as some join points (thus must *not* float
2872 -- past the continuation!).
2873 -- Hence, the full story is this:
2874 -- K[case _ of { p1 -> r1; ...; pn -> rn }] ==>
2875 -- F_v[Knodup[F_j[ (case _ of { p1 -> Kdup[r1]; ...; pn -> Kdup[rn] }) ]]]
2876 -- Here F_v represents some values that got floated out and F_j represents some
2877 -- join points that got floated out.
2878 --
2879 -- When case-of-case is off, just make the entire continuation non-dupable
2880
2881 prepareCaseCont env alts cont
2882 | not (altsWouldDup alts)
2883 = return (env, cont, mkBoringStop (contResultType cont))
2884 | otherwise
2885 = do { (env', cont') <- mkDupableCont env cont
2886 ; return (env', cont', mkBoringStop (contResultType cont)) }
2887
2888 prepareJoinCont :: SimplEnv -> SimplCont -> SimplM (SimplEnv, SimplCont)
2889
2890 -- Similar to prepareCaseCont, only for
2891 -- K[let { j1 = r1; ...; jn -> rn } in _]
2892 -- If the js are join points, this will turn into
2893 -- Knodup[join { j1 = Kdup[r1]; ...; jn = Kdup[rn] } in Kdup[_]].
2894 --
2895 -- When case-of-case is off and it's a join binding, just make the entire
2896 -- continuation non-dupable. This is necessary because otherwise
2897 -- case (join j = ... in case e of { A -> jump j 1; ... }) of { B -> ... }
2898 -- becomes
2899 -- join j = case ... of { B -> ... } in
2900 -- case (case e of { A -> jump j 1; ... }) of { B -> ... },
2901 -- and the reference to j is invalid.
2902
2903 prepareJoinCont env cont
2904 = mkDupableCont env cont
2905
2906 altsWouldDup :: [InAlt] -> Bool -- True iff strictly > 1 non-bottom alternative
2907 altsWouldDup [] = False -- See Note [Bottom alternatives]
2908 altsWouldDup [_] = False
2909 altsWouldDup (alt:alts)
2910 | is_bot_alt alt = altsWouldDup alts
2911 | otherwise = not (all is_bot_alt alts)
2912 where
2913 is_bot_alt (_,_,rhs) = exprIsBottom rhs
2914
2915 {-
2916 Note [Bottom alternatives]
2917 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2918 When we have
2919 case (case x of { A -> error .. ; B -> e; C -> error ..)
2920 of alts
2921 then we can just duplicate those alts because the A and C cases
2922 will disappear immediately. This is more direct than creating
2923 join points and inlining them away. See Trac #4930.
2924 -}
2925
2926 -------------------------
2927 mkDupableCont :: SimplEnv -> SimplCont
2928 -> SimplM ( SimplEnv -- Incoming SimplEnv augmented with
2929 -- extra let/join-floats and in-scope variables
2930 , SimplCont) -- dup_cont: duplicable continuation
2931 mkDupableCont env cont
2932 = mk_dupable_cont env cont
2933
2934 -------------------------
2935 mk_dupable_cont :: SimplEnv -> SimplCont
2936 -> SimplM (SimplEnv, SimplCont)
2937 mk_dupable_cont env cont
2938 | contIsDupable cont
2939 = return (env, cont)
2940
2941 mk_dupable_cont _ (Stop {}) = panic "mkDupableCont" -- Handled by previous eqn
2942
2943 mk_dupable_cont env (CastIt ty cont)
2944 = do { (env', cont') <- mk_dupable_cont env cont
2945 ; return (env', CastIt ty cont') }
2946
2947 -- Duplicating ticks for now, not sure if this is good or not
2948 mk_dupable_cont env (TickIt t cont)
2949 = do { (env', cont') <- mk_dupable_cont env cont
2950 ; return (env', TickIt t cont') }
2951
2952 mk_dupable_cont env (StrictBind { sc_bndr = bndr, sc_bndrs = bndrs
2953 , sc_body = body, sc_env = se, sc_cont = cont})
2954 -- See Note [Duplicating StrictBind]
2955 = do { let sb_env = se `setInScopeAndZapFloats` env
2956 ; (sb_env1, bndr') <- simplBinder sb_env bndr
2957 ; (sb_env', join_inner) <- simplLam sb_env1 bndrs body cont
2958 -- No need to use mk_dupable_cont before simplLam; we
2959 -- use cont once here, and then share the result if necessary
2960 ; let join_body = wrapFloats sb_env' join_inner
2961 res_ty = contResultType cont
2962 ; dflags <- getDynFlags
2963 ; (env2, body2)
2964 <- if exprIsDupable dflags join_body
2965 then return (env, join_body)
2966 else do { join_bndr <- newJoinId [bndr'] res_ty
2967 ; let join_call = App (Var join_bndr) (Var bndr')
2968 join_rhs = Lam (setOneShotLambda bndr') join_body
2969 ; return (addNonRec env join_bndr join_rhs, join_call) }
2970 ; return ( env2
2971 , StrictBind { sc_bndr = bndr', sc_bndrs = []
2972 , sc_body = body2
2973 , sc_env = zapSubstEnv se
2974 , sc_dup = OkToDup
2975 , sc_cont = mkBoringStop res_ty } ) }
2976
2977 mk_dupable_cont env (StrictArg { sc_fun = info, sc_cci = cci, sc_cont = cont })
2978 -- See Note [Duplicating StrictArg]
2979 -- NB: sc_dup /= OkToDup; that is caught earlier by contIsDupable
2980 = do { (env', cont') <- mk_dupable_cont env cont
2981 ; (env'', args') <- mapAccumLM makeTrivialArg env' (ai_args info)
2982 ; return (env'', StrictArg { sc_fun = info { ai_args = args' }
2983 , sc_cci = cci
2984 , sc_cont = cont'
2985 , sc_dup = OkToDup} ) }
2986
2987 mk_dupable_cont env (ApplyToTy { sc_cont = cont
2988 , sc_arg_ty = arg_ty, sc_hole_ty = hole_ty })
2989 = do { (env', cont') <- mk_dupable_cont env cont
2990 ; return (env', ApplyToTy { sc_cont = cont'
2991 , sc_arg_ty = arg_ty, sc_hole_ty = hole_ty }) }
2992
2993 mk_dupable_cont env (ApplyToVal { sc_arg = arg, sc_dup = dup
2994 , sc_env = se, sc_cont = cont })
2995 = -- e.g. [...hole...] (...arg...)
2996 -- ==>
2997 -- let a = ...arg...
2998 -- in [...hole...] a
2999 -- NB: sc_dup /= OkToDup; that is caught earlier by contIsDupable
3000 do { (env', cont') <- mk_dupable_cont env cont
3001 ; (_, se', arg') <- simplArg env' dup se arg
3002 ; (env'', arg'') <- makeTrivial NotTopLevel env' (fsLit "karg") arg'
3003 ; return (env'', ApplyToVal { sc_arg = arg'', sc_env = se'
3004 , sc_dup = OkToDup, sc_cont = cont' }) }
3005
3006 mk_dupable_cont env (Select { sc_bndr = case_bndr, sc_alts = alts
3007 , sc_env = se, sc_cont = cont })
3008 = -- e.g. (case [...hole...] of { pi -> ei })
3009 -- ===>
3010 -- let ji = \xij -> ei
3011 -- in case [...hole...] of { pi -> ji xij }
3012 -- NB: sc_dup /= OkToDup; that is caught earlier by contIsDupable
3013 do { tick (CaseOfCase case_bndr)
3014 ; (env', alt_cont, wrap_cont) <- prepareCaseCont env alts cont
3015 -- NB: We call prepareCaseCont here. If there is only one
3016 -- alternative, then dup_cont may be big, but that's ok
3017 -- because we push it into the single alternative, and then
3018 -- use mkDupableAlt to turn that simplified alternative into
3019 -- a join point if it's too big to duplicate.
3020 -- And this is important: see Note [Fusing case continuations]
3021
3022 ; let alt_env = se `setInScopeAndZapFloats` env'
3023
3024 ; (alt_env', case_bndr') <- simplBinder alt_env case_bndr
3025 ; alts' <- mapM (simplAlt alt_env' Nothing [] case_bndr' alt_cont) alts
3026 -- Safe to say that there are no handled-cons for the DEFAULT case
3027 -- NB: simplBinder does not zap deadness occ-info, so
3028 -- a dead case_bndr' will still advertise its deadness
3029 -- This is really important because in
3030 -- case e of b { (# p,q #) -> ... }
3031 -- b is always dead, and indeed we are not allowed to bind b to (# p,q #),
3032 -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
3033 -- In the new alts we build, we have the new case binder, so it must retain
3034 -- its deadness.
3035 -- NB: we don't use alt_env further; it has the substEnv for
3036 -- the alternatives, and we don't want that
3037
3038 ; (join_binds, alts'') <- mkDupableAlts case_bndr' alts'
3039 ; let env'' = foldl (\env (j,r) -> addNonRec env j r) env' join_binds
3040
3041 ; return (env'', -- Note [Duplicated env]
3042 Select { sc_dup = OkToDup
3043 , sc_bndr = case_bndr', sc_alts = alts''
3044 , sc_env = zapSubstEnv env''
3045 , sc_cont = wrap_cont } ) }
3046
3047 mkDupableAlts :: OutId -> [OutAlt] -> SimplM ([(JoinId, OutExpr)], [OutAlt])
3048 mkDupableAlts case_bndr' the_alts
3049 = do { dflags <- getDynFlags
3050 ; (mb_join_floats, dup_alts)
3051 <- mapAndUnzipM (mkDupableAlt dflags case_bndr') the_alts
3052 ; return (catMaybes mb_join_floats, dup_alts) }
3053
3054 mkDupableAlt :: DynFlags -> OutId -> OutAlt
3055 -> SimplM (Maybe (JoinId,OutExpr), OutAlt)
3056 mkDupableAlt dflags case_bndr (con, bndrs', rhs')
3057 | exprIsDupable dflags rhs' -- Note [Small alternative rhs]
3058 = return (Nothing, (con, bndrs', rhs'))
3059
3060 | otherwise
3061 = do { let rhs_ty' = exprType rhs'
3062 scrut_ty = idType case_bndr
3063 case_bndr_w_unf
3064 = case con of
3065 DEFAULT -> case_bndr
3066 DataAlt dc -> setIdUnfolding case_bndr unf
3067 where
3068 -- See Note [Case binders and join points]
3069 unf = mkInlineUnfolding rhs
3070 rhs = mkConApp2 dc (tyConAppArgs scrut_ty) bndrs'
3071
3072 LitAlt {} -> WARN( True, text "mkDupableAlt"
3073 <+> ppr case_bndr <+> ppr con )
3074 case_bndr
3075 -- The case binder is alive but trivial, so why has
3076 -- it not been substituted away?
3077
3078 final_bndrs'
3079 | isDeadBinder case_bndr = filter abstract_over bndrs'
3080 | otherwise = bndrs' ++ [case_bndr_w_unf]
3081
3082 abstract_over bndr
3083 | isTyVar bndr = True -- Abstract over all type variables just in case
3084 | otherwise = not (isDeadBinder bndr)
3085 -- The deadness info on the new Ids is preserved by simplBinders
3086 final_args = varsToCoreExprs final_bndrs'
3087 -- Note [Join point abstraction]
3088
3089 -- We make the lambdas into one-shot-lambdas. The
3090 -- join point is sure to be applied at most once, and doing so
3091 -- prevents the body of the join point being floated out by
3092 -- the full laziness pass
3093 really_final_bndrs = map one_shot final_bndrs'
3094 one_shot v | isId v = setOneShotLambda v
3095 | otherwise = v
3096 join_rhs = mkLams really_final_bndrs rhs'
3097
3098 ; join_bndr <- newJoinId final_bndrs' rhs_ty'
3099
3100 ; let join_call = mkApps (Var join_bndr) final_args
3101 alt' = (con, bndrs', join_call)
3102
3103 ; return (Just (join_bndr, join_rhs), alt') }
3104 -- See Note [Duplicated env]
3105
3106 {-
3107 Note [Fusing case continuations]
3108 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3109 It's important to fuse two successive case continuations when the
3110 first has one alternative. That's why we call prepareCaseCont here.
3111 Consider this, which arises from thunk splitting (see Note [Thunk
3112 splitting] in WorkWrap):
3113
3114 let
3115 x* = case (case v of {pn -> rn}) of
3116 I# a -> I# a
3117 in body
3118
3119 The simplifier will find
3120 (Var v) with continuation
3121 Select (pn -> rn) (
3122 Select [I# a -> I# a] (
3123 StrictBind body Stop
3124
3125 So we'll call mkDupableCont on
3126 Select [I# a -> I# a] (StrictBind body Stop)
3127 There is just one alternative in the first Select, so we want to
3128 simplify the rhs (I# a) with continuation (StrictBind body Stop)
3129 Supposing that body is big, we end up with
3130 let $j a = <let x = I# a in body>
3131 in case v of { pn -> case rn of
3132 I# a -> $j a }
3133 This is just what we want because the rn produces a box that
3134 the case rn cancels with.
3135
3136 See Trac #4957 a fuller example.
3137
3138 Note [Case binders and join points]
3139 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3140 Consider this
3141 case (case .. ) of c {
3142 I# c# -> ....c....
3143
3144 If we make a join point with c but not c# we get
3145 $j = \c -> ....c....
3146
3147 But if later inlining scrutinises the c, thus
3148
3149 $j = \c -> ... case c of { I# y -> ... } ...
3150
3151 we won't see that 'c' has already been scrutinised. This actually
3152 happens in the 'tabulate' function in wave4main, and makes a significant
3153 difference to allocation.
3154
3155 An alternative plan is this:
3156
3157 $j = \c# -> let c = I# c# in ...c....
3158
3159 but that is bad if 'c' is *not* later scrutinised.
3160
3161 So instead we do both: we pass 'c' and 'c#' , and record in c's inlining
3162 (a stable unfolding) that it's really I# c#, thus
3163
3164 $j = \c# -> \c[=I# c#] -> ...c....
3165
3166 Absence analysis may later discard 'c'.
3167
3168 NB: take great care when doing strictness analysis;
3169 see Note [Lambda-bound unfoldings] in DmdAnal.
3170
3171 Also note that we can still end up passing stuff that isn't used. Before
3172 strictness analysis we have
3173 let $j x y c{=(x,y)} = (h c, ...)
3174 in ...
3175 After strictness analysis we see that h is strict, we end up with
3176 let $j x y c{=(x,y)} = ($wh x y, ...)
3177 and c is unused.
3178
3179 Note [Duplicated env]
3180 ~~~~~~~~~~~~~~~~~~~~~
3181 Some of the alternatives are simplified, but have not been turned into a join point
3182 So they *must* have an zapped subst-env. So we can't use completeNonRecX to
3183 bind the join point, because it might to do PostInlineUnconditionally, and
3184 we'd lose that when zapping the subst-env. We could have a per-alt subst-env,
3185 but zapping it (as we do in mkDupableCont, the Select case) is safe, and
3186 at worst delays the join-point inlining.
3187
3188 Note [Small alternative rhs]
3189 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3190 It is worth checking for a small RHS because otherwise we
3191 get extra let bindings that may cause an extra iteration of the simplifier to
3192 inline back in place. Quite often the rhs is just a variable or constructor.
3193 The Ord instance of Maybe in PrelMaybe.hs, for example, took several extra
3194 iterations because the version with the let bindings looked big, and so wasn't
3195 inlined, but after the join points had been inlined it looked smaller, and so
3196 was inlined.
3197
3198 NB: we have to check the size of rhs', not rhs.
3199 Duplicating a small InAlt might invalidate occurrence information
3200 However, if it *is* dupable, we return the *un* simplified alternative,
3201 because otherwise we'd need to pair it up with an empty subst-env....
3202 but we only have one env shared between all the alts.
3203 (Remember we must zap the subst-env before re-simplifying something).
3204 Rather than do this we simply agree to re-simplify the original (small) thing later.
3205
3206 Note [Funky mkLamTypes]
3207 ~~~~~~~~~~~~~~~~~~~~~~
3208 Notice the funky mkLamTypes. If the constructor has existentials
3209 it's possible that the join point will be abstracted over
3210 type variables as well as term variables.
3211 Example: Suppose we have
3212 data T = forall t. C [t]
3213 Then faced with
3214 case (case e of ...) of
3215 C t xs::[t] -> rhs
3216 We get the join point
3217 let j :: forall t. [t] -> ...
3218 j = /\t \xs::[t] -> rhs
3219 in
3220 case (case e of ...) of
3221 C t xs::[t] -> j t xs
3222
3223 Note [Duplicating StrictArg]
3224 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3225 We make a StrictArg duplicable simply by making all its
3226 stored-up arguments (in sc_fun) trivial, by let-binding
3227 them. Thus:
3228 f E [..hole..]
3229 ==> let a = E
3230 in f a [..hole..]
3231 Now if the thing in the hole is a case expression (which is when
3232 we'll call mkDupableCont), we'll push the function call into the
3233 branches, which is what we want. Now RULES for f may fire, and
3234 call-pattern specialisation. Here's an example from Trac #3116
3235 go (n+1) (case l of
3236 1 -> bs'
3237 _ -> Chunk p fpc (o+1) (l-1) bs')
3238 If we can push the call for 'go' inside the case, we get
3239 call-pattern specialisation for 'go', which is *crucial* for
3240 this program.
3241
3242 Here is the (&&) example:
3243 && E (case x of { T -> F; F -> T })
3244 ==> let a = E in
3245 case x of { T -> && a F; F -> && a T }
3246 Much better!
3247
3248 Notice that
3249 * Arguments to f *after* the strict one are handled by
3250 the ApplyToVal case of mkDupableCont. Eg
3251 f [..hole..] E
3252
3253 * We can only do the let-binding of E because the function
3254 part of a StrictArg continuation is an explicit syntax
3255 tree. In earlier versions we represented it as a function
3256 (CoreExpr -> CoreEpxr) which we couldn't take apart.
3257
3258 Historical aide: previously we did this (where E is a
3259 big argument:
3260 f E [..hole..]
3261 ==> let $j = \a -> f E a
3262 in $j [..hole..]
3263
3264 But this is terrible! Here's an example:
3265 && E (case x of { T -> F; F -> T })
3266 Now, && is strict so we end up simplifying the case with
3267 an ArgOf continuation. If we let-bind it, we get
3268 let $j = \v -> && E v
3269 in simplExpr (case x of { T -> F; F -> T })
3270 (ArgOf (\r -> $j r)
3271 And after simplifying more we get
3272 let $j = \v -> && E v
3273 in case x of { T -> $j F; F -> $j T }
3274 Which is a Very Bad Thing
3275
3276
3277 Note [Duplicating StrictBind]
3278 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3279 We make a StrictBind duplicable in a very similar way to
3280 that for case expressions. After all,
3281 let x* = e in b is similar to case e of x -> b
3282
3283 So we potentially make a join-point for the body, thus:
3284 let x = [] in b ==> join j x = b
3285 in let x = [] in j x
3286
3287
3288 Note [Join point abstraction] Historical note
3289 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3290 NB: This note is now historical, describing how (in the past) we used
3291 to add a void argument to nullary join points. But now that "join
3292 point" is not a fuzzy concept but a formal syntactic construct (as
3293 distinguished by the JoinId constructor of IdDetails), each of these
3294 concerns is handled separately, with no need for a vestigial extra
3295 argument.
3296
3297 Join points always have at least one value argument,
3298 for several reasons
3299
3300 * If we try to lift a primitive-typed something out
3301 for let-binding-purposes, we will *caseify* it (!),
3302 with potentially-disastrous strictness results. So
3303 instead we turn it into a function: \v -> e
3304 where v::Void#. The value passed to this function is void,
3305 which generates (almost) no code.
3306
3307 * CPR. We used to say "&& isUnliftedType rhs_ty'" here, but now
3308 we make the join point into a function whenever used_bndrs'
3309 is empty. This makes the join-point more CPR friendly.
3310 Consider: let j = if .. then I# 3 else I# 4
3311 in case .. of { A -> j; B -> j; C -> ... }
3312
3313 Now CPR doesn't w/w j because it's a thunk, so
3314 that means that the enclosing function can't w/w either,
3315 which is a lose. Here's the example that happened in practice:
3316 kgmod :: Int -> Int -> Int
3317 kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
3318 then 78
3319 else 5
3320
3321 * Let-no-escape. We want a join point to turn into a let-no-escape
3322 so that it is implemented as a jump, and one of the conditions
3323 for LNE is that it's not updatable. In CoreToStg, see
3324 Note [What is a non-escaping let]
3325
3326 * Floating. Since a join point will be entered once, no sharing is
3327 gained by floating out, but something might be lost by doing
3328 so because it might be allocated.
3329
3330 I have seen a case alternative like this:
3331 True -> \v -> ...
3332 It's a bit silly to add the realWorld dummy arg in this case, making
3333 $j = \s v -> ...
3334 True -> $j s
3335 (the \v alone is enough to make CPR happy) but I think it's rare
3336
3337 There's a slight infelicity here: we pass the overall
3338 case_bndr to all the join points if it's used in *any* RHS,
3339 because we don't know its usage in each RHS separately
3340
3341
3342
3343 ************************************************************************
3344 * *
3345 Unfoldings
3346 * *
3347 ************************************************************************
3348 -}
3349
3350 simplLetUnfolding :: SimplEnv-> TopLevelFlag
3351 -> Maybe SimplCont
3352 -> InId
3353 -> OutExpr
3354 -> Unfolding -> SimplM Unfolding
3355 simplLetUnfolding env top_lvl cont_mb id new_rhs unf
3356 | isStableUnfolding unf
3357 = simplUnfolding env top_lvl cont_mb id unf
3358 | otherwise
3359 = is_bottoming `seq` -- See Note [Force bottoming field]
3360 do { dflags <- getDynFlags
3361 ; return (mkUnfolding dflags InlineRhs is_top_lvl is_bottoming new_rhs) }
3362 -- We make an unfolding *even for loop-breakers*.
3363 -- Reason: (a) It might be useful to know that they are WHNF
3364 -- (b) In TidyPgm we currently assume that, if we want to
3365 -- expose the unfolding then indeed we *have* an unfolding
3366 -- to expose. (We could instead use the RHS, but currently
3367 -- we don't.) The simple thing is always to have one.
3368 where
3369 is_top_lvl = isTopLevel top_lvl
3370 is_bottoming = isBottomingId id
3371
3372 simplUnfolding :: SimplEnv -> TopLevelFlag
3373 -> Maybe SimplCont -- Just k => a join point with continuation k
3374 -> InId
3375 -> Unfolding -> SimplM Unfolding
3376 -- Note [Setting the new unfolding]
3377 simplUnfolding env top_lvl mb_cont id unf
3378 = case unf of
3379 NoUnfolding -> return unf
3380 BootUnfolding -> return unf
3381 OtherCon {} -> return unf
3382
3383 DFunUnfolding { df_bndrs = bndrs, df_con = con, df_args = args }
3384 -> do { (env', bndrs') <- simplBinders rule_env bndrs
3385 ; args' <- mapM (simplExpr env') args
3386 ; return (mkDFunUnfolding bndrs' con args') }
3387
3388 CoreUnfolding { uf_tmpl = expr, uf_src = src, uf_guidance = guide }
3389 | isStableSource src
3390 -> do { expr' <- case mb_cont of
3391 Just cont -> simplJoinRhs rule_env id expr cont
3392 Nothing -> simplExpr rule_env expr
3393 ; case guide of
3394 UnfWhen { ug_arity = arity, ug_unsat_ok = sat_ok } -- Happens for INLINE things
3395 -> let guide' = UnfWhen { ug_arity = arity, ug_unsat_ok = sat_ok
3396 , ug_boring_ok = inlineBoringOk expr' }
3397 -- Refresh the boring-ok flag, in case expr'
3398 -- has got small. This happens, notably in the inlinings
3399 -- for dfuns for single-method classes; see
3400 -- Note [Single-method classes] in TcInstDcls.
3401 -- A test case is Trac #4138
3402 in return (mkCoreUnfolding src is_top_lvl expr' guide')
3403 -- See Note [Top-level flag on inline rules] in CoreUnfold
3404
3405 _other -- Happens for INLINABLE things
3406 -> is_bottoming `seq` -- See Note [Force bottoming field]
3407 do { dflags <- getDynFlags
3408 ; return (mkUnfolding dflags src is_top_lvl is_bottoming expr') } }
3409 -- If the guidance is UnfIfGoodArgs, this is an INLINABLE
3410 -- unfolding, and we need to make sure the guidance is kept up
3411 -- to date with respect to any changes in the unfolding.
3412
3413 | otherwise -> return noUnfolding -- Discard unstable unfoldings
3414 where
3415 is_top_lvl = isTopLevel top_lvl
3416 is_bottoming = isBottomingId id
3417 act = idInlineActivation id
3418 rule_env = updMode (updModeForStableUnfoldings act) env
3419 -- See Note [Simplifying inside stable unfoldings] in SimplUtils
3420
3421 {-
3422 Note [Force bottoming field]
3423 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3424 We need to force bottoming, or the new unfolding holds
3425 on to the old unfolding (which is part of the id).
3426
3427 Note [Setting the new unfolding]
3428 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3429 * If there's an INLINE pragma, we simplify the RHS gently. Maybe we
3430 should do nothing at all, but simplifying gently might get rid of
3431 more crap.
3432
3433 * If not, we make an unfolding from the new RHS. But *only* for
3434 non-loop-breakers. Making loop breakers not have an unfolding at all
3435 means that we can avoid tests in exprIsConApp, for example. This is
3436 important: if exprIsConApp says 'yes' for a recursive thing, then we
3437 can get into an infinite loop
3438
3439 If there's an stable unfolding on a loop breaker (which happens for
3440 INLINABLE), we hang on to the inlining. It's pretty dodgy, but the
3441 user did say 'INLINE'. May need to revisit this choice.
3442
3443 ************************************************************************
3444 * *
3445 Rules
3446 * *
3447 ************************************************************************
3448
3449 Note [Rules in a letrec]
3450 ~~~~~~~~~~~~~~~~~~~~~~~~
3451 After creating fresh binders for the binders of a letrec, we
3452 substitute the RULES and add them back onto the binders; this is done
3453 *before* processing any of the RHSs. This is important. Manuel found
3454 cases where he really, really wanted a RULE for a recursive function
3455 to apply in that function's own right-hand side.
3456
3457 See Note [Forming Rec groups] in OccurAnal
3458 -}
3459
3460 addBndrRules :: SimplEnv -> InBndr -> OutBndr -> SimplM (SimplEnv, OutBndr)
3461 -- Rules are added back into the bin
3462 addBndrRules env in_id out_id
3463 | null old_rules
3464 = return (env, out_id)
3465 | otherwise
3466 = do { new_rules <- simplRules env (Just (idName out_id)) old_rules
3467 ; let final_id = out_id `setIdSpecialisation` mkRuleInfo new_rules
3468 ; return (modifyInScope env final_id, final_id) }
3469 where
3470 old_rules = ruleInfoRules (idSpecialisation in_id)
3471
3472 simplRules :: SimplEnv -> Maybe Name -> [CoreRule] -> SimplM [CoreRule]
3473 simplRules env mb_new_nm rules
3474 = mapM simpl_rule rules
3475 where
3476 simpl_rule rule@(BuiltinRule {})
3477 = return rule
3478
3479 simpl_rule rule@(Rule { ru_bndrs = bndrs, ru_args = args
3480 , ru_fn = fn_name, ru_rhs = rhs })
3481 = do { (env', bndrs') <- simplBinders env bndrs
3482 ; let rhs_ty = substTy env' (exprType rhs)
3483 rule_cont = mkBoringStop rhs_ty
3484 rule_env = updMode updModeForRules env'
3485 ; args' <- mapM (simplExpr rule_env) args
3486 ; rhs' <- simplExprC rule_env rhs rule_cont
3487 ; return (rule { ru_bndrs = bndrs'
3488 , ru_fn = mb_new_nm `orElse` fn_name
3489 , ru_args = args'
3490 , ru_rhs = rhs' }) }