Zap stable unfoldings in worker/wrapper
[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 = zapStableUnfolding bndr
1523 | otherwise = bndr
1524
1525 -- discard a non-counting tick on a lambda. This may change the
1526 -- cost attribution slightly (moving the allocation of the
1527 -- lambda elsewhere), but we don't care: optimisation changes
1528 -- cost attribution all the time.
1529 simplLam env bndrs body (TickIt tickish cont)
1530 | not (tickishCounts tickish)
1531 = simplLam env bndrs body cont
1532
1533 -- Not enough args, so there are real lambdas left to put in the result
1534 simplLam env bndrs body cont
1535 = do { (env', bndrs') <- simplLamBndrs env bndrs
1536 ; body' <- simplExpr env' body
1537 ; new_lam <- mkLam env bndrs' body' cont
1538 ; rebuild env' new_lam cont }
1539
1540 simplLamBndrs :: SimplEnv -> [InBndr] -> SimplM (SimplEnv, [OutBndr])
1541 simplLamBndrs env bndrs = mapAccumLM simplLamBndr env bndrs
1542
1543 -------------
1544 simplLamBndr :: SimplEnv -> InBndr -> SimplM (SimplEnv, OutBndr)
1545 -- Used for lambda binders. These sometimes have unfoldings added by
1546 -- the worker/wrapper pass that must be preserved, because they can't
1547 -- be reconstructed from context. For example:
1548 -- f x = case x of (a,b) -> fw a b x
1549 -- fw a b x{=(a,b)} = ...
1550 -- The "{=(a,b)}" is an unfolding we can't reconstruct otherwise.
1551 simplLamBndr env bndr
1552 | isId bndr && isFragileUnfolding old_unf -- Special case
1553 = do { (env1, bndr1) <- simplBinder env bndr
1554 ; unf' <- simplUnfolding env1 NotTopLevel Nothing bndr old_unf
1555 ; let bndr2 = bndr1 `setIdUnfolding` unf'
1556 ; return (modifyInScope env1 bndr2, bndr2) }
1557
1558 | otherwise
1559 = simplBinder env bndr -- Normal case
1560 where
1561 old_unf = idUnfolding bndr
1562
1563 ------------------
1564 simplNonRecE :: SimplEnv
1565 -> InId -- The binder, always an Id
1566 -- Can be a join point
1567 -> (InExpr, SimplEnv) -- Rhs of binding (or arg of lambda)
1568 -> ([InBndr], InExpr) -- Body of the let/lambda
1569 -- \xs.e
1570 -> SimplCont
1571 -> SimplM (SimplEnv, OutExpr)
1572
1573 -- simplNonRecE is used for
1574 -- * non-top-level non-recursive lets in expressions
1575 -- * beta reduction
1576 --
1577 -- simplNonRec env b (rhs, rhs_se) (bs, body) k
1578 -- = let env in
1579 -- cont< let b = rhs_se(rhs) in \bs.body >
1580 --
1581 -- It deals with strict bindings, via the StrictBind continuation,
1582 -- which may abort the whole process
1583 --
1584 -- Precondition: rhs satisfies the let/app invariant
1585 -- Note [CoreSyn let/app invariant] in CoreSyn
1586 --
1587 -- The "body" of the binding comes as a pair of ([InId],InExpr)
1588 -- representing a lambda; so we recurse back to simplLam
1589 -- Why? Because of the binder-occ-info-zapping done before
1590 -- the call to simplLam in simplExprF (Lam ...)
1591
1592 simplNonRecE env bndr (rhs, rhs_se) (bndrs, body) cont
1593 = ASSERT( isId bndr )
1594 do dflags <- getDynFlags
1595 case () of
1596 _ | preInlineUnconditionally dflags env NotTopLevel bndr rhs
1597 -> do { tick (PreInlineUnconditionally bndr)
1598 ; -- pprTrace "preInlineUncond" (ppr bndr <+> ppr rhs) $
1599 simplLam (extendIdSubst env bndr (mkContEx rhs_se rhs)) bndrs body cont }
1600
1601 -- Deal with join points
1602 | Just (bndr', rhs') <- joinPointBinding_maybe bndr rhs
1603 -> ASSERT( null bndrs ) -- Must be a let-binding;
1604 -- join points are never lambda-bound
1605 do { (env1, cont') <- prepareJoinCont env cont
1606
1607 -- We push cont_dup into the join RHS and the body;
1608 -- and wrap cont_nodup around the whole thing
1609 ; let res_ty = contResultType cont'
1610 ; (env2, bndr1) <- simplNonRecJoinBndr env1 res_ty bndr'
1611 ; (env3, bndr2) <- addBndrRules env2 bndr' bndr1
1612 ; env4 <- simplJoinBind env3 NonRecursive cont'
1613 bndr' bndr2 rhs' rhs_se
1614 ; simplExprF env4 body cont' }
1615
1616 -- Deal with strict bindings
1617 | isStrictId bndr -- Includes coercions
1618 , sm_case_case (getMode env)
1619 -> simplExprF (rhs_se `setFloats` env) rhs
1620 (StrictBind { sc_bndr = bndr, sc_bndrs = bndrs, sc_body = body
1621 , sc_env = env, sc_cont = cont, sc_dup = NoDup })
1622
1623 -- Deal with lazy bindings
1624 | otherwise
1625 -> ASSERT( not (isTyVar bndr) )
1626 do { (env1, bndr1) <- simplNonRecBndr env bndr
1627 ; (env2, bndr2) <- addBndrRules env1 bndr bndr1
1628 ; env3 <- simplLazyBind env2 NotTopLevel NonRecursive bndr bndr2 rhs rhs_se
1629 ; simplLam env3 bndrs body cont }
1630
1631 ------------------
1632 simplRecE :: SimplEnv
1633 -> [(InId, InExpr)]
1634 -> InExpr
1635 -> SimplCont
1636 -> SimplM (SimplEnv, OutExpr)
1637
1638 -- simplRecE is used for
1639 -- * non-top-level recursive lets in expressions
1640 simplRecE env pairs body cont
1641 | Just pairs' <- joinPointBindings_maybe pairs
1642 = do { (env1, cont') <- prepareJoinCont env cont
1643 ; let bndrs' = map fst pairs'
1644 res_ty = contResultType cont
1645 ; env2 <- simplRecJoinBndrs env1 res_ty bndrs'
1646 -- NB: bndrs' don't have unfoldings or rules
1647 -- We add them as we go down
1648 ; env3 <- simplRecBind env2 NotTopLevel (Just cont') pairs'
1649 ; simplExprF env3 body cont' }
1650
1651 | otherwise
1652 = do { let bndrs = map fst pairs
1653 ; MASSERT(all (not . isJoinId) bndrs)
1654 ; env1 <- simplRecBndrs env bndrs
1655 -- NB: bndrs' don't have unfoldings or rules
1656 -- We add them as we go down
1657 ; env2 <- simplRecBind env1 NotTopLevel Nothing pairs
1658 ; simplExprF env2 body cont }
1659
1660 {-
1661 ************************************************************************
1662 * *
1663 Variables
1664 * *
1665 ************************************************************************
1666 -}
1667
1668 simplVar :: SimplEnv -> InVar -> SimplM OutExpr
1669 -- Look up an InVar in the environment
1670 simplVar env var
1671 | isTyVar var = return (Type (substTyVar env var))
1672 | isCoVar var = return (Coercion (substCoVar env var))
1673 | otherwise
1674 = case substId env var of
1675 ContEx tvs cvs ids e -> simplExpr (setSubstEnv env tvs cvs ids) e
1676 DoneId var1 -> return (Var var1)
1677 DoneEx e _ -> return e
1678
1679 simplIdF :: SimplEnv -> InId -> SimplCont -> SimplM (SimplEnv, OutExpr)
1680 simplIdF env var cont
1681 = case substId env var of
1682 ContEx tvs cvs ids e -> simplExprF (setSubstEnv env tvs cvs ids) e cont
1683 -- Don't trim; haven't already simplified e,
1684 -- so the cont is not embodied in e
1685
1686 DoneId var1 -> completeCall env var1 (trim_cont (isJoinId_maybe var1))
1687 DoneEx e mb_join -> simplExprF (zapSubstEnv env) e (trim_cont mb_join)
1688 -- Note [zapSubstEnv]
1689 -- The template is already simplified, so don't re-substitute.
1690 -- This is VITAL. Consider
1691 -- let x = e in
1692 -- let y = \z -> ...x... in
1693 -- \ x -> ...y...
1694 -- We'll clone the inner \x, adding x->x' in the id_subst
1695 -- Then when we inline y, we must *not* replace x by x' in
1696 -- the inlined copy!!
1697 where
1698 trim_cont (Just arity) = trim arity cont
1699 trim_cont Nothing = cont
1700
1701 -- Drop outer context from join point invocation
1702 -- Note [Case-of-case and join points]
1703 trim 0 cont@(Stop {})
1704 = cont
1705 trim 0 cont
1706 = mkBoringStop (contResultType cont)
1707 trim n cont@(ApplyToVal { sc_cont = k })
1708 = cont { sc_cont = trim (n-1) k }
1709 trim n cont@(ApplyToTy { sc_cont = k })
1710 = cont { sc_cont = trim (n-1) k } -- join arity counts types!
1711 trim _ cont
1712 = pprPanic "completeCall" $ ppr var $$ ppr cont
1713
1714 ---------------------------------------------------------
1715 -- Dealing with a call site
1716
1717 completeCall :: SimplEnv -> OutId -> SimplCont -> SimplM (SimplEnv, OutExpr)
1718 completeCall env var cont
1719 = do { ------------- Try inlining ----------------
1720 dflags <- getDynFlags
1721 ; let (lone_variable, arg_infos, call_cont) = contArgs cont
1722 n_val_args = length arg_infos
1723 interesting_cont = interestingCallContext call_cont
1724 unfolding = activeUnfolding env var
1725 maybe_inline = callSiteInline dflags var unfolding
1726 lone_variable arg_infos interesting_cont
1727 ; case maybe_inline of
1728 Just expr -- There is an inlining!
1729 -> do { checkedTick (UnfoldingDone var)
1730 ; dump_inline dflags expr cont
1731 ; simplExprF (zapSubstEnv env) expr cont }
1732
1733 ; Nothing -> do { rule_base <- getSimplRules
1734 ; let info = mkArgInfo var (getRules rule_base var)
1735 n_val_args call_cont
1736 ; rebuildCall env info cont }
1737 }
1738 where
1739 dump_inline dflags unfolding cont
1740 | not (dopt Opt_D_dump_inlinings dflags) = return ()
1741 | not (dopt Opt_D_verbose_core2core dflags)
1742 = when (isExternalName (idName var)) $
1743 liftIO $ printOutputForUser dflags alwaysQualify $
1744 sep [text "Inlining done:", nest 4 (ppr var)]
1745 | otherwise
1746 = liftIO $ printOutputForUser dflags alwaysQualify $
1747 sep [text "Inlining done: " <> ppr var,
1748 nest 4 (vcat [text "Inlined fn: " <+> nest 2 (ppr unfolding),
1749 text "Cont: " <+> ppr cont])]
1750
1751 rebuildCall :: SimplEnv
1752 -> ArgInfo
1753 -> SimplCont
1754 -> SimplM (SimplEnv, OutExpr)
1755 -- We decided not to inline, so
1756 -- - simplify the arguments
1757 -- - try rewrite rules
1758 -- - and rebuild
1759
1760 ---------- Bottoming applications --------------
1761 rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args, ai_strs = [] }) cont
1762 -- When we run out of strictness args, it means
1763 -- that the call is definitely bottom; see SimplUtils.mkArgInfo
1764 -- Then we want to discard the entire strict continuation. E.g.
1765 -- * case (error "hello") of { ... }
1766 -- * (error "Hello") arg
1767 -- * f (error "Hello") where f is strict
1768 -- etc
1769 -- Then, especially in the first of these cases, we'd like to discard
1770 -- the continuation, leaving just the bottoming expression. But the
1771 -- type might not be right, so we may have to add a coerce.
1772 | not (contIsTrivial cont) -- Only do this if there is a non-trivial
1773 -- continuation to discard, else we do it
1774 -- again and again!
1775 = seqType cont_ty `seq` -- See Note [Avoiding space leaks in OutType]
1776 return (env, castBottomExpr res cont_ty)
1777 where
1778 res = argInfoExpr fun rev_args
1779 cont_ty = contResultType cont
1780
1781 ---------- Try rewrite RULES --------------
1782 -- See Note [Trying rewrite rules]
1783 rebuildCall env info@(ArgInfo { ai_fun = fun, ai_args = rev_args
1784 , ai_rules = Just (nr_wanted, rules) }) cont
1785 | nr_wanted == 0 || no_more_args
1786 , let info' = info { ai_rules = Nothing }
1787 = -- We've accumulated a simplified call in <fun,rev_args>
1788 -- so try rewrite rules; see Note [RULEs apply to simplified arguments]
1789 -- See also Note [Rules for recursive functions]
1790 do { mb_match <- tryRules env rules fun (reverse rev_args) cont
1791 ; case mb_match of
1792 Just (env', rhs, cont') -> simplExprF env' rhs cont'
1793 Nothing -> rebuildCall env info' cont }
1794 where
1795 no_more_args = case cont of
1796 ApplyToTy {} -> False
1797 ApplyToVal {} -> False
1798 _ -> True
1799
1800
1801 ---------- Simplify applications and casts --------------
1802 rebuildCall env info (CastIt co cont)
1803 = rebuildCall env (addCastTo info co) cont
1804
1805 rebuildCall env info (ApplyToTy { sc_arg_ty = arg_ty, sc_cont = cont })
1806 = rebuildCall env (addTyArgTo info arg_ty) cont
1807
1808 rebuildCall env info@(ArgInfo { ai_encl = encl_rules, ai_type = fun_ty
1809 , ai_strs = str:strs, ai_discs = disc:discs })
1810 (ApplyToVal { sc_arg = arg, sc_env = arg_se
1811 , sc_dup = dup_flag, sc_cont = cont })
1812 | isSimplified dup_flag -- See Note [Avoid redundant simplification]
1813 = rebuildCall env (addValArgTo info' arg) cont
1814
1815 | str -- Strict argument
1816 , sm_case_case (getMode env)
1817 = -- pprTrace "Strict Arg" (ppr arg $$ ppr (seIdSubst env) $$ ppr (seInScope env)) $
1818 simplExprF (arg_se `setFloats` env) arg
1819 (StrictArg { sc_fun = info', sc_cci = cci_strict
1820 , sc_dup = Simplified, sc_cont = cont })
1821 -- Note [Shadowing]
1822
1823 | otherwise -- Lazy argument
1824 -- DO NOT float anything outside, hence simplExprC
1825 -- There is no benefit (unlike in a let-binding), and we'd
1826 -- have to be very careful about bogus strictness through
1827 -- floating a demanded let.
1828 = do { arg' <- simplExprC (arg_se `setInScopeAndZapFloats` env) arg
1829 (mkLazyArgStop arg_ty cci_lazy)
1830 ; rebuildCall env (addValArgTo info' arg') cont }
1831 where
1832 info' = info { ai_strs = strs, ai_discs = discs }
1833 arg_ty = funArgTy fun_ty
1834
1835 -- Use this for lazy arguments
1836 cci_lazy | encl_rules = RuleArgCtxt
1837 | disc > 0 = DiscArgCtxt -- Be keener here
1838 | otherwise = BoringCtxt -- Nothing interesting
1839
1840 -- ..and this for strict arguments
1841 cci_strict | encl_rules = RuleArgCtxt
1842 | disc > 0 = DiscArgCtxt
1843 | otherwise = RhsCtxt
1844 -- Why RhsCtxt? if we see f (g x) (h x), and f is strict, we
1845 -- want to be a bit more eager to inline g, because it may
1846 -- expose an eval (on x perhaps) that can be eliminated or
1847 -- shared. I saw this in nofib 'boyer2', RewriteFuns.onewayunify1
1848 -- It's worth an 18% improvement in allocation for this
1849 -- particular benchmark; 5% on 'mate' and 1.3% on 'multiplier'
1850
1851 ---------- No further useful info, revert to generic rebuild ------------
1852 rebuildCall env (ArgInfo { ai_fun = fun, ai_args = rev_args }) cont
1853 = rebuild env (argInfoExpr fun rev_args) cont
1854
1855 {- Note [Trying rewrite rules]
1856 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1857 Consider an application (f e1 e2 e3) where the e1,e2,e3 are not yet
1858 simplified. We want to simplify enough arguments to allow the rules
1859 to apply, but it's more efficient to avoid simplifying e2,e3 if e1 alone
1860 is sufficient. Example: class ops
1861 (+) dNumInt e2 e3
1862 If we rewrite ((+) dNumInt) to plusInt, we can take advantage of the
1863 latter's strictness when simplifying e2, e3. Moreover, suppose we have
1864 RULE f Int = \x. x True
1865
1866 Then given (f Int e1) we rewrite to
1867 (\x. x True) e1
1868 without simpifying e1. Now we can inline x into its unique call site,
1869 and absorb the True into it all in the same pass. If we simplified
1870 e1 first, we couldn't do that; see Note [Avoiding exponential behaviour].
1871
1872 So we try to apply rules if either
1873 (a) no_more_args: we've run out of argument that the rules can "see"
1874 (b) nr_wanted: none of the rules wants any more arguments
1875
1876
1877 Note [RULES apply to simplified arguments]
1878 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1879 It's very desirable to try RULES once the arguments have been simplified, because
1880 doing so ensures that rule cascades work in one pass. Consider
1881 {-# RULES g (h x) = k x
1882 f (k x) = x #-}
1883 ...f (g (h x))...
1884 Then we want to rewrite (g (h x)) to (k x) and only then try f's rules. If
1885 we match f's rules against the un-simplified RHS, it won't match. This
1886 makes a particularly big difference when superclass selectors are involved:
1887 op ($p1 ($p2 (df d)))
1888 We want all this to unravel in one sweep.
1889
1890 Note [Avoid redundant simplification]
1891 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1892 Because RULES apply to simplified arguments, there's a danger of repeatedly
1893 simplifying already-simplified arguments. An important example is that of
1894 (>>=) d e1 e2
1895 Here e1, e2 are simplified before the rule is applied, but don't really
1896 participate in the rule firing. So we mark them as Simplified to avoid
1897 re-simplifying them.
1898
1899 Note [Shadowing]
1900 ~~~~~~~~~~~~~~~~
1901 This part of the simplifier may break the no-shadowing invariant
1902 Consider
1903 f (...(\a -> e)...) (case y of (a,b) -> e')
1904 where f is strict in its second arg
1905 If we simplify the innermost one first we get (...(\a -> e)...)
1906 Simplifying the second arg makes us float the case out, so we end up with
1907 case y of (a,b) -> f (...(\a -> e)...) e'
1908 So the output does not have the no-shadowing invariant. However, there is
1909 no danger of getting name-capture, because when the first arg was simplified
1910 we used an in-scope set that at least mentioned all the variables free in its
1911 static environment, and that is enough.
1912
1913 We can't just do innermost first, or we'd end up with a dual problem:
1914 case x of (a,b) -> f e (...(\a -> e')...)
1915
1916 I spent hours trying to recover the no-shadowing invariant, but I just could
1917 not think of an elegant way to do it. The simplifier is already knee-deep in
1918 continuations. We have to keep the right in-scope set around; AND we have
1919 to get the effect that finding (error "foo") in a strict arg position will
1920 discard the entire application and replace it with (error "foo"). Getting
1921 all this at once is TOO HARD!
1922
1923
1924 ************************************************************************
1925 * *
1926 Rewrite rules
1927 * *
1928 ************************************************************************
1929 -}
1930
1931 tryRules :: SimplEnv -> [CoreRule]
1932 -> Id -> [ArgSpec]
1933 -> SimplCont
1934 -> SimplM (Maybe (SimplEnv, CoreExpr, SimplCont))
1935
1936 tryRules env rules fn args call_cont
1937 | null rules
1938 = return Nothing
1939 {- Disabled until we fix #8326
1940 | fn `hasKey` tagToEnumKey -- See Note [Optimising tagToEnum#]
1941 , [_type_arg, val_arg] <- args
1942 , Select dup bndr ((_,[],rhs1) : rest_alts) se cont <- call_cont
1943 , isDeadBinder bndr
1944 = do { dflags <- getDynFlags
1945 ; let enum_to_tag :: CoreAlt -> CoreAlt
1946 -- Takes K -> e into tagK# -> e
1947 -- where tagK# is the tag of constructor K
1948 enum_to_tag (DataAlt con, [], rhs)
1949 = ASSERT( isEnumerationTyCon (dataConTyCon con) )
1950 (LitAlt tag, [], rhs)
1951 where
1952 tag = mkMachInt dflags (toInteger (dataConTag con - fIRST_TAG))
1953 enum_to_tag alt = pprPanic "tryRules: tagToEnum" (ppr alt)
1954
1955 new_alts = (DEFAULT, [], rhs1) : map enum_to_tag rest_alts
1956 new_bndr = setIdType bndr intPrimTy
1957 -- The binder is dead, but should have the right type
1958 ; return (Just (val_arg, Select dup new_bndr new_alts se cont)) }
1959 -}
1960 | otherwise
1961 = do { dflags <- getDynFlags
1962 ; case lookupRule dflags (getUnfoldingInRuleMatch env) (activeRule env)
1963 fn (argInfoAppArgs args) rules of {
1964 Nothing ->
1965 do { nodump dflags -- This ensures that an empty file is written
1966 ; return Nothing } ; -- No rule matches
1967 Just (rule, rule_rhs) ->
1968 do { checkedTick (RuleFired (ruleName rule))
1969 ; let cont' = pushSimplifiedArgs zapped_env
1970 (drop (ruleArity rule) args)
1971 call_cont
1972 -- (ruleArity rule) says how
1973 -- many args the rule consumed
1974
1975 occ_anald_rhs = occurAnalyseExpr rule_rhs
1976 -- See Note [Occurrence-analyse after rule firing]
1977 ; dump dflags rule rule_rhs
1978 ; return (Just (zapped_env, occ_anald_rhs, cont')) }}}
1979 -- The occ_anald_rhs and cont' are all Out things
1980 -- hence zapping the environment
1981 where
1982 zapped_env = zapSubstEnv env -- See Note [zapSubstEnv]
1983
1984 printRuleModule rule =
1985 parens
1986 (maybe (text "BUILTIN") (pprModuleName . moduleName) (ruleModule rule))
1987
1988 dump dflags rule rule_rhs
1989 | dopt Opt_D_dump_rule_rewrites dflags
1990 = log_rule dflags Opt_D_dump_rule_rewrites "Rule fired" $ vcat
1991 [ text "Rule:" <+> ftext (ruleName rule)
1992 , text "Module:" <+> printRuleModule rule
1993 , text "Before:" <+> hang (ppr fn) 2 (sep (map ppr args))
1994 , text "After: " <+> pprCoreExpr rule_rhs
1995 , text "Cont: " <+> ppr call_cont ]
1996
1997 | dopt Opt_D_dump_rule_firings dflags
1998 = log_rule dflags Opt_D_dump_rule_firings "Rule fired:" $
1999 ftext (ruleName rule)
2000 <+> printRuleModule rule
2001
2002 | otherwise
2003 = return ()
2004
2005 nodump dflags
2006 | dopt Opt_D_dump_rule_rewrites dflags
2007 = liftIO $ dumpSDoc dflags alwaysQualify Opt_D_dump_rule_rewrites "" empty
2008
2009 | dopt Opt_D_dump_rule_firings dflags
2010 = liftIO $ dumpSDoc dflags alwaysQualify Opt_D_dump_rule_firings "" empty
2011
2012 | otherwise
2013 = return ()
2014
2015 log_rule dflags flag hdr details
2016 = liftIO . dumpSDoc dflags alwaysQualify flag "" $
2017 sep [text hdr, nest 4 details]
2018
2019 trySeqRules :: SimplEnv
2020 -> OutExpr -> InExpr -- Scrutinee and RHS
2021 -> SimplCont
2022 -> SimplM (Maybe (SimplEnv, CoreExpr, SimplCont))
2023 -- See Note [User-defined RULES for seq]
2024 trySeqRules in_env scrut rhs cont
2025 = do { rule_base <- getSimplRules
2026 ; tryRules in_env (getRules rule_base seqId) seqId out_args rule_cont }
2027 where
2028 no_cast_scrut = drop_casts scrut
2029 scrut_ty = exprType no_cast_scrut
2030 seq_id_ty = idType seqId
2031 rhs_ty = substTy in_env (exprType rhs)
2032 out_args = [ TyArg { as_arg_ty = scrut_ty
2033 , as_hole_ty = seq_id_ty }
2034 , TyArg { as_arg_ty = rhs_ty
2035 , as_hole_ty = piResultTy seq_id_ty scrut_ty }
2036 , ValArg no_cast_scrut]
2037 rule_cont = ApplyToVal { sc_dup = NoDup, sc_arg = rhs
2038 , sc_env = in_env, sc_cont = cont }
2039 -- Lazily evaluated, so we don't do most of this
2040
2041 drop_casts (Cast e _) = drop_casts e
2042 drop_casts e = e
2043
2044 {- Note [User-defined RULES for seq]
2045 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2046 Given
2047 case (scrut |> co) of _ -> rhs
2048 look for rules that match the expression
2049 seq @t1 @t2 scrut
2050 where scrut :: t1
2051 rhs :: t2
2052
2053 If you find a match, rewrite it, and apply to 'rhs'.
2054
2055 Notice that we can simply drop casts on the fly here, which
2056 makes it more likely that a rule will match.
2057
2058 See Note [User-defined RULES for seq] in MkId.
2059
2060 Note [Occurrence-analyse after rule firing]
2061 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2062 After firing a rule, we occurrence-analyse the instantiated RHS before
2063 simplifying it. Usually this doesn't make much difference, but it can
2064 be huge. Here's an example (simplCore/should_compile/T7785)
2065
2066 map f (map f (map f xs)
2067
2068 = -- Use build/fold form of map, twice
2069 map f (build (\cn. foldr (mapFB c f) n
2070 (build (\cn. foldr (mapFB c f) n xs))))
2071
2072 = -- Apply fold/build rule
2073 map f (build (\cn. (\cn. foldr (mapFB c f) n xs) (mapFB c f) n))
2074
2075 = -- Beta-reduce
2076 -- Alas we have no occurrence-analysed, so we don't know
2077 -- that c is used exactly once
2078 map f (build (\cn. let c1 = mapFB c f in
2079 foldr (mapFB c1 f) n xs))
2080
2081 = -- Use mapFB rule: mapFB (mapFB c f) g = mapFB c (f.g)
2082 -- We can do this because (mapFB c n) is a PAP and hence expandable
2083 map f (build (\cn. let c1 = mapFB c n in
2084 foldr (mapFB c (f.f)) n x))
2085
2086 This is not too bad. But now do the same with the outer map, and
2087 we get another use of mapFB, and t can interact with /both/ remaining
2088 mapFB calls in the above expression. This is stupid because actually
2089 that 'c1' binding is dead. The outer map introduces another c2. If
2090 there is a deep stack of maps we get lots of dead bindings, and lots
2091 of redundant work as we repeatedly simplify the result of firing rules.
2092
2093 The easy thing to do is simply to occurrence analyse the result of
2094 the rule firing. Note that this occ-anals not only the RHS of the
2095 rule, but also the function arguments, which by now are OutExprs.
2096 E.g.
2097 RULE f (g x) = x+1
2098
2099 Call f (g BIG) --> (\x. x+1) BIG
2100
2101 The rule binders are lambda-bound and applied to the OutExpr arguments
2102 (here BIG) which lack all internal occurrence info.
2103
2104 Is this inefficient? Not really: we are about to walk over the result
2105 of the rule firing to simplify it, so occurrence analysis is at most
2106 a constant factor.
2107
2108 Possible improvement: occ-anal the rules when putting them in the
2109 database; and in the simplifier just occ-anal the OutExpr arguments.
2110 But that's more complicated and the rule RHS is usually tiny; so I'm
2111 just doing the simple thing.
2112
2113 Historical note: previously we did occ-anal the rules in Rule.hs,
2114 but failed to occ-anal the OutExpr arguments, which led to the
2115 nasty performance problem described above.
2116
2117
2118 Note [Optimising tagToEnum#]
2119 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2120 If we have an enumeration data type:
2121
2122 data Foo = A | B | C
2123
2124 Then we want to transform
2125
2126 case tagToEnum# x of ==> case x of
2127 A -> e1 DEFAULT -> e1
2128 B -> e2 1# -> e2
2129 C -> e3 2# -> e3
2130
2131 thereby getting rid of the tagToEnum# altogether. If there was a DEFAULT
2132 alternative we retain it (remember it comes first). If not the case must
2133 be exhaustive, and we reflect that in the transformed version by adding
2134 a DEFAULT. Otherwise Lint complains that the new case is not exhaustive.
2135 See #8317.
2136
2137 Note [Rules for recursive functions]
2138 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2139 You might think that we shouldn't apply rules for a loop breaker:
2140 doing so might give rise to an infinite loop, because a RULE is
2141 rather like an extra equation for the function:
2142 RULE: f (g x) y = x+y
2143 Eqn: f a y = a-y
2144
2145 But it's too drastic to disable rules for loop breakers.
2146 Even the foldr/build rule would be disabled, because foldr
2147 is recursive, and hence a loop breaker:
2148 foldr k z (build g) = g k z
2149 So it's up to the programmer: rules can cause divergence
2150
2151
2152 ************************************************************************
2153 * *
2154 Rebuilding a case expression
2155 * *
2156 ************************************************************************
2157
2158 Note [Case elimination]
2159 ~~~~~~~~~~~~~~~~~~~~~~~
2160 The case-elimination transformation discards redundant case expressions.
2161 Start with a simple situation:
2162
2163 case x# of ===> let y# = x# in e
2164 y# -> e
2165
2166 (when x#, y# are of primitive type, of course). We can't (in general)
2167 do this for algebraic cases, because we might turn bottom into
2168 non-bottom!
2169
2170 The code in SimplUtils.prepareAlts has the effect of generalise this
2171 idea to look for a case where we're scrutinising a variable, and we
2172 know that only the default case can match. For example:
2173
2174 case x of
2175 0# -> ...
2176 DEFAULT -> ...(case x of
2177 0# -> ...
2178 DEFAULT -> ...) ...
2179
2180 Here the inner case is first trimmed to have only one alternative, the
2181 DEFAULT, after which it's an instance of the previous case. This
2182 really only shows up in eliminating error-checking code.
2183
2184 Note that SimplUtils.mkCase combines identical RHSs. So
2185
2186 case e of ===> case e of DEFAULT -> r
2187 True -> r
2188 False -> r
2189
2190 Now again the case may be elminated by the CaseElim transformation.
2191 This includes things like (==# a# b#)::Bool so that we simplify
2192 case ==# a# b# of { True -> x; False -> x }
2193 to just
2194 x
2195 This particular example shows up in default methods for
2196 comparison operations (e.g. in (>=) for Int.Int32)
2197
2198 Note [Case elimination: lifted case]
2199 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2200 If a case over a lifted type has a single alternative, and is being used
2201 as a strict 'let' (all isDeadBinder bndrs), we may want to do this
2202 transformation:
2203
2204 case e of r ===> let r = e in ...r...
2205 _ -> ...r...
2206
2207 (a) 'e' is already evaluated (it may so if e is a variable)
2208 Specifically we check (exprIsHNF e). In this case
2209 we can just allocate the WHNF directly with a let.
2210 or
2211 (b) 'x' is not used at all and e is ok-for-speculation
2212 The ok-for-spec bit checks that we don't lose any
2213 exceptions or divergence.
2214
2215 NB: it'd be *sound* to switch from case to let if the
2216 scrutinee was not yet WHNF but was guaranteed to
2217 converge; but sticking with case means we won't build a
2218 thunk
2219
2220 or
2221 (c) 'x' is used strictly in the body, and 'e' is a variable
2222 Then we can just substitute 'e' for 'x' in the body.
2223 See Note [Eliminating redundant seqs]
2224
2225 For (b), the "not used at all" test is important. Consider
2226 case (case a ># b of { True -> (p,q); False -> (q,p) }) of
2227 r -> blah
2228 The scrutinee is ok-for-speculation (it looks inside cases), but we do
2229 not want to transform to
2230 let r = case a ># b of { True -> (p,q); False -> (q,p) }
2231 in blah
2232 because that builds an unnecessary thunk.
2233
2234 Note [Eliminating redundant seqs]
2235 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2236 If we have this:
2237 case x of r { _ -> ..r.. }
2238 where 'r' is used strictly in (..r..), the case is effectively a 'seq'
2239 on 'x', but since 'r' is used strictly anyway, we can safely transform to
2240 (...x...)
2241
2242 Note that this can change the error behaviour. For example, we might
2243 transform
2244 case x of { _ -> error "bad" }
2245 --> error "bad"
2246 which is might be puzzling if 'x' currently lambda-bound, but later gets
2247 let-bound to (error "good").
2248
2249 Nevertheless, the paper "A semantics for imprecise exceptions" allows
2250 this transformation. If you want to fix the evaluation order, use
2251 'pseq'. See Trac #8900 for an example where the loss of this
2252 transformation bit us in practice.
2253
2254 See also Note [Empty case alternatives] in CoreSyn.
2255
2256 Just for reference, the original code (added Jan 13) looked like this:
2257 || case_bndr_evald_next rhs
2258
2259 case_bndr_evald_next :: CoreExpr -> Bool
2260 -- See Note [Case binder next]
2261 case_bndr_evald_next (Var v) = v == case_bndr
2262 case_bndr_evald_next (Cast e _) = case_bndr_evald_next e
2263 case_bndr_evald_next (App e _) = case_bndr_evald_next e
2264 case_bndr_evald_next (Case e _ _ _) = case_bndr_evald_next e
2265 case_bndr_evald_next _ = False
2266
2267 (This came up when fixing Trac #7542. See also Note [Eta reduction of
2268 an eval'd function] in CoreUtils.)
2269
2270
2271 Note [Case elimination: unlifted case]
2272 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2273 Consider
2274 case a +# b of r -> ...r...
2275 Then we do case-elimination (to make a let) followed by inlining,
2276 to get
2277 .....(a +# b)....
2278 If we have
2279 case indexArray# a i of r -> ...r...
2280 we might like to do the same, and inline the (indexArray# a i).
2281 But indexArray# is not okForSpeculation, so we don't build a let
2282 in rebuildCase (lest it get floated *out*), so the inlining doesn't
2283 happen either.
2284
2285 This really isn't a big deal I think. The let can be
2286
2287
2288 Further notes about case elimination
2289 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2290 Consider: test :: Integer -> IO ()
2291 test = print
2292
2293 Turns out that this compiles to:
2294 Print.test
2295 = \ eta :: Integer
2296 eta1 :: Void# ->
2297 case PrelNum.< eta PrelNum.zeroInteger of wild { __DEFAULT ->
2298 case hPutStr stdout
2299 (PrelNum.jtos eta ($w[] @ Char))
2300 eta1
2301 of wild1 { (# new_s, a4 #) -> PrelIO.lvl23 new_s }}
2302
2303 Notice the strange '<' which has no effect at all. This is a funny one.
2304 It started like this:
2305
2306 f x y = if x < 0 then jtos x
2307 else if y==0 then "" else jtos x
2308
2309 At a particular call site we have (f v 1). So we inline to get
2310
2311 if v < 0 then jtos x
2312 else if 1==0 then "" else jtos x
2313
2314 Now simplify the 1==0 conditional:
2315
2316 if v<0 then jtos v else jtos v
2317
2318 Now common-up the two branches of the case:
2319
2320 case (v<0) of DEFAULT -> jtos v
2321
2322 Why don't we drop the case? Because it's strict in v. It's technically
2323 wrong to drop even unnecessary evaluations, and in practice they
2324 may be a result of 'seq' so we *definitely* don't want to drop those.
2325 I don't really know how to improve this situation.
2326 -}
2327
2328 ---------------------------------------------------------
2329 -- Eliminate the case if possible
2330
2331 rebuildCase, reallyRebuildCase
2332 :: SimplEnv
2333 -> OutExpr -- Scrutinee
2334 -> InId -- Case binder
2335 -> [InAlt] -- Alternatives (inceasing order)
2336 -> SimplCont
2337 -> SimplM (SimplEnv, OutExpr)
2338
2339 --------------------------------------------------
2340 -- 1. Eliminate the case if there's a known constructor
2341 --------------------------------------------------
2342
2343 rebuildCase env scrut case_bndr alts cont
2344 | Lit lit <- scrut -- No need for same treatment as constructors
2345 -- because literals are inlined more vigorously
2346 , not (litIsLifted lit)
2347 = do { tick (KnownBranch case_bndr)
2348 ; case findAlt (LitAlt lit) alts of
2349 Nothing -> missingAlt env case_bndr alts cont
2350 Just (_, bs, rhs) -> simple_rhs bs rhs }
2351
2352 | Just (con, ty_args, other_args) <- exprIsConApp_maybe (getUnfoldingInRuleMatch env) scrut
2353 -- Works when the scrutinee is a variable with a known unfolding
2354 -- as well as when it's an explicit constructor application
2355 = do { tick (KnownBranch case_bndr)
2356 ; case findAlt (DataAlt con) alts of
2357 Nothing -> missingAlt env case_bndr alts cont
2358 Just (DEFAULT, bs, rhs) -> simple_rhs bs rhs
2359 Just (_, bs, rhs) -> knownCon env scrut con ty_args other_args
2360 case_bndr bs rhs cont
2361 }
2362 where
2363 simple_rhs bs rhs = ASSERT( null bs )
2364 do { env' <- simplNonRecX env case_bndr scrut
2365 -- scrut is a constructor application,
2366 -- hence satisfies let/app invariant
2367 ; simplExprF env' rhs cont }
2368
2369
2370 --------------------------------------------------
2371 -- 2. Eliminate the case if scrutinee is evaluated
2372 --------------------------------------------------
2373
2374 rebuildCase env scrut case_bndr alts@[(_, bndrs, rhs)] cont
2375 -- See if we can get rid of the case altogether
2376 -- See Note [Case elimination]
2377 -- mkCase made sure that if all the alternatives are equal,
2378 -- then there is now only one (DEFAULT) rhs
2379
2380 -- 2a. Dropping the case altogether, if
2381 -- a) it binds nothing (so it's really just a 'seq')
2382 -- b) evaluating the scrutinee has no side effects
2383 | is_plain_seq
2384 , exprOkForSideEffects scrut
2385 -- The entire case is dead, so we can drop it
2386 -- if the scrutinee converges without having imperative
2387 -- side effects or raising a Haskell exception
2388 -- See Note [PrimOp can_fail and has_side_effects] in PrimOp
2389 = simplExprF env rhs cont
2390
2391 -- 2b. Turn the case into a let, if
2392 -- a) it binds only the case-binder
2393 -- b) unlifted case: the scrutinee is ok-for-speculation
2394 -- lifted case: the scrutinee is in HNF (or will later be demanded)
2395 | all_dead_bndrs
2396 , if is_unlifted
2397 then exprOkForSpeculation scrut -- See Note [Case elimination: unlifted case]
2398 else exprIsHNF scrut -- See Note [Case elimination: lifted case]
2399 || scrut_is_demanded_var scrut
2400 = do { tick (CaseElim case_bndr)
2401 ; env' <- simplNonRecX env case_bndr scrut
2402 ; simplExprF env' rhs cont }
2403
2404 -- 2c. Try the seq rules if
2405 -- a) it binds only the case binder
2406 -- b) a rule for seq applies
2407 -- See Note [User-defined RULES for seq] in MkId
2408 | is_plain_seq
2409 = do { mb_rule <- trySeqRules env scrut rhs cont
2410 ; case mb_rule of
2411 Just (env', rule_rhs, cont') -> simplExprF env' rule_rhs cont'
2412 Nothing -> reallyRebuildCase env scrut case_bndr alts cont }
2413 where
2414 is_unlifted = isUnliftedType (idType case_bndr)
2415 all_dead_bndrs = all isDeadBinder bndrs -- bndrs are [InId]
2416 is_plain_seq = all_dead_bndrs && isDeadBinder case_bndr -- Evaluation *only* for effect
2417
2418 scrut_is_demanded_var :: CoreExpr -> Bool
2419 -- See Note [Eliminating redundant seqs]
2420 scrut_is_demanded_var (Cast s _) = scrut_is_demanded_var s
2421 scrut_is_demanded_var (Var _) = isStrictDmd (idDemandInfo case_bndr)
2422 scrut_is_demanded_var _ = False
2423
2424
2425 rebuildCase env scrut case_bndr alts cont
2426 = reallyRebuildCase env scrut case_bndr alts cont
2427
2428 --------------------------------------------------
2429 -- 3. Catch-all case
2430 --------------------------------------------------
2431
2432 reallyRebuildCase env scrut case_bndr alts cont
2433 = do { -- Prepare the continuation;
2434 -- The new subst_env is in place
2435 (env, alt_cont, wrap_cont) <- prepareCaseCont env alts cont
2436
2437 -- Simplify the alternatives
2438 ; (scrut', case_bndr', alts') <- simplAlts env scrut case_bndr alts alt_cont
2439
2440 ; dflags <- getDynFlags
2441 ; let alts_ty' = contResultType alt_cont
2442 -- See Note [Avoiding space leaks in OutType]
2443 ; case_expr <- seqType alts_ty' `seq`
2444 mkCase dflags scrut' case_bndr' alts_ty' alts'
2445
2446 -- Notice that rebuild gets the in-scope set from env', not alt_env
2447 -- (which in any case is only build in simplAlts)
2448 -- The case binder *not* scope over the whole returned case-expression
2449 ; rebuild env case_expr wrap_cont }
2450
2451 {-
2452 simplCaseBinder checks whether the scrutinee is a variable, v. If so,
2453 try to eliminate uses of v in the RHSs in favour of case_bndr; that
2454 way, there's a chance that v will now only be used once, and hence
2455 inlined.
2456
2457 Historical note: we use to do the "case binder swap" in the Simplifier
2458 so there were additional complications if the scrutinee was a variable.
2459 Now the binder-swap stuff is done in the occurrence analyser; see
2460 OccurAnal Note [Binder swap].
2461
2462 Note [knownCon occ info]
2463 ~~~~~~~~~~~~~~~~~~~~~~~~
2464 If the case binder is not dead, then neither are the pattern bound
2465 variables:
2466 case <any> of x { (a,b) ->
2467 case x of { (p,q) -> p } }
2468 Here (a,b) both look dead, but come alive after the inner case is eliminated.
2469 The point is that we bring into the envt a binding
2470 let x = (a,b)
2471 after the outer case, and that makes (a,b) alive. At least we do unless
2472 the case binder is guaranteed dead.
2473
2474 Note [Case alternative occ info]
2475 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2476 When we are simply reconstructing a case (the common case), we always
2477 zap the occurrence info on the binders in the alternatives. Even
2478 if the case binder is dead, the scrutinee is usually a variable, and *that*
2479 can bring the case-alternative binders back to life.
2480 See Note [Add unfolding for scrutinee]
2481
2482 Note [Improving seq]
2483 ~~~~~~~~~~~~~~~~~~~
2484 Consider
2485 type family F :: * -> *
2486 type instance F Int = Int
2487
2488 We'd like to transform
2489 case e of (x :: F Int) { DEFAULT -> rhs }
2490 ===>
2491 case e `cast` co of (x'::Int)
2492 I# x# -> let x = x' `cast` sym co
2493 in rhs
2494
2495 so that 'rhs' can take advantage of the form of x'. Notice that Note
2496 [Case of cast] (in OccurAnal) may then apply to the result.
2497
2498 We'd also like to eliminate empty types (Trac #13468). So if
2499
2500 data Void
2501 type instance F Bool = Void
2502
2503 then we'd like to transform
2504 case (x :: F Bool) of { _ -> error "urk" }
2505 ===>
2506 case (x |> co) of (x' :: Void) of {}
2507
2508 Nota Bene: we used to have a built-in rule for 'seq' that dropped
2509 casts, so that
2510 case (x |> co) of { _ -> blah }
2511 dropped the cast; in order to improve the chances of trySeqRules
2512 firing. But that works in the /opposite/ direction to Note [Improving
2513 seq] so there's a danger of flip/flopping. Better to make trySeqRules
2514 insensitive to the cast, which is now is.
2515
2516 The need for [Improving seq] showed up in Roman's experiments. Example:
2517 foo :: F Int -> Int -> Int
2518 foo t n = t `seq` bar n
2519 where
2520 bar 0 = 0
2521 bar n = bar (n - case t of TI i -> i)
2522 Here we'd like to avoid repeated evaluating t inside the loop, by
2523 taking advantage of the `seq`.
2524
2525 At one point I did transformation in LiberateCase, but it's more
2526 robust here. (Otherwise, there's a danger that we'll simply drop the
2527 'seq' altogether, before LiberateCase gets to see it.)
2528 -}
2529
2530 simplAlts :: SimplEnv
2531 -> OutExpr
2532 -> InId -- Case binder
2533 -> [InAlt] -- Non-empty
2534 -> SimplCont
2535 -> SimplM (OutExpr, OutId, [OutAlt]) -- Includes the continuation
2536 -- Like simplExpr, this just returns the simplified alternatives;
2537 -- it does not return an environment
2538 -- The returned alternatives can be empty, none are possible
2539
2540 simplAlts env scrut case_bndr alts cont'
2541 = do { let env0 = zapFloats env
2542
2543 ; (env1, case_bndr1) <- simplBinder env0 case_bndr
2544 ; let case_bndr2 = case_bndr1 `setIdUnfolding` evaldUnfolding
2545 env2 = modifyInScope env1 case_bndr2
2546 -- See Note [Case binder evaluated-ness]
2547
2548 ; fam_envs <- getFamEnvs
2549 ; (alt_env', scrut', case_bndr') <- improveSeq fam_envs env2 scrut
2550 case_bndr case_bndr2 alts
2551
2552 ; (imposs_deflt_cons, in_alts) <- prepareAlts scrut' case_bndr' alts
2553 -- NB: it's possible that the returned in_alts is empty: this is handled
2554 -- by the caller (rebuildCase) in the missingAlt function
2555
2556 ; alts' <- mapM (simplAlt alt_env' (Just scrut') imposs_deflt_cons case_bndr' cont') in_alts
2557 ; -- pprTrace "simplAlts" (ppr case_bndr $$ ppr alts_ty $$ ppr alts_ty' $$ ppr alts $$ ppr cont') $
2558 return (scrut', case_bndr', alts') }
2559
2560
2561 ------------------------------------
2562 improveSeq :: (FamInstEnv, FamInstEnv) -> SimplEnv
2563 -> OutExpr -> InId -> OutId -> [InAlt]
2564 -> SimplM (SimplEnv, OutExpr, OutId)
2565 -- Note [Improving seq]
2566 improveSeq fam_envs env scrut case_bndr case_bndr1 [(DEFAULT,_,_)]
2567 | Just (co, ty2) <- topNormaliseType_maybe fam_envs (idType case_bndr1)
2568 = do { case_bndr2 <- newId (fsLit "nt") ty2
2569 ; let rhs = DoneEx (Var case_bndr2 `Cast` mkSymCo co) Nothing
2570 env2 = extendIdSubst env case_bndr rhs
2571 ; return (env2, scrut `Cast` co, case_bndr2) }
2572
2573 improveSeq _ env scrut _ case_bndr1 _
2574 = return (env, scrut, case_bndr1)
2575
2576
2577 ------------------------------------
2578 simplAlt :: SimplEnv
2579 -> Maybe OutExpr -- The scrutinee
2580 -> [AltCon] -- These constructors can't be present when
2581 -- matching the DEFAULT alternative
2582 -> OutId -- The case binder
2583 -> SimplCont
2584 -> InAlt
2585 -> SimplM OutAlt
2586
2587 simplAlt env _ imposs_deflt_cons case_bndr' cont' (DEFAULT, bndrs, rhs)
2588 = ASSERT( null bndrs )
2589 do { let env' = addBinderUnfolding env case_bndr'
2590 (mkOtherCon imposs_deflt_cons)
2591 -- Record the constructors that the case-binder *can't* be.
2592 ; rhs' <- simplExprC env' rhs cont'
2593 ; return (DEFAULT, [], rhs') }
2594
2595 simplAlt env scrut' _ case_bndr' cont' (LitAlt lit, bndrs, rhs)
2596 = ASSERT( null bndrs )
2597 do { env' <- addAltUnfoldings env scrut' case_bndr' (Lit lit)
2598 ; rhs' <- simplExprC env' rhs cont'
2599 ; return (LitAlt lit, [], rhs') }
2600
2601 simplAlt env scrut' _ case_bndr' cont' (DataAlt con, vs, rhs)
2602 = do { -- Deal with the pattern-bound variables
2603 -- Mark the ones that are in ! positions in the
2604 -- data constructor as certainly-evaluated.
2605 -- NB: simplLamBinders preserves this eval info
2606 ; let vs_with_evals = add_evals (dataConRepStrictness con)
2607 ; (env', vs') <- simplLamBndrs env vs_with_evals
2608
2609 -- Bind the case-binder to (con args)
2610 ; let inst_tys' = tyConAppArgs (idType case_bndr')
2611 con_app :: OutExpr
2612 con_app = mkConApp2 con inst_tys' vs'
2613
2614 ; env'' <- addAltUnfoldings env' scrut' case_bndr' con_app
2615 ; rhs' <- simplExprC env'' rhs cont'
2616 ; return (DataAlt con, vs', rhs') }
2617 where
2618 -- add_evals records the evaluated-ness of the bound variables of
2619 -- a case pattern. This is *important*. Consider
2620 -- data T = T !Int !Int
2621 --
2622 -- case x of { T a b -> T (a+1) b }
2623 --
2624 -- We really must record that b is already evaluated so that we don't
2625 -- go and re-evaluate it when constructing the result.
2626 -- See Note [Data-con worker strictness] in MkId.hs
2627 add_evals the_strs
2628 = go vs the_strs
2629 where
2630 go [] [] = []
2631 go (v:vs') strs | isTyVar v = v : go vs' strs
2632 go (v:vs') (str:strs) = zap str v : go vs' strs
2633 go _ _ = pprPanic "cat_evals"
2634 (ppr con $$
2635 ppr vs $$
2636 ppr_with_length the_strs $$
2637 ppr_with_length (dataConRepArgTys con) $$
2638 ppr_with_length (dataConRepStrictness con))
2639 where
2640 ppr_with_length list
2641 = ppr list <+> parens (text "length =" <+> ppr (length list))
2642 -- NB: If this panic triggers, note that
2643 -- NoStrictnessMark doesn't print!
2644
2645 zap str v = setCaseBndrEvald str $ -- Add eval'dness info
2646 zapIdOccInfo v -- And kill occ info;
2647 -- see Note [Case alternative occ info]
2648
2649 addAltUnfoldings :: SimplEnv -> Maybe OutExpr -> OutId -> OutExpr -> SimplM SimplEnv
2650 addAltUnfoldings env scrut case_bndr con_app
2651 = do { dflags <- getDynFlags
2652 ; let con_app_unf = mkSimpleUnfolding dflags con_app
2653 env1 = addBinderUnfolding env case_bndr con_app_unf
2654
2655 -- See Note [Add unfolding for scrutinee]
2656 env2 = case scrut of
2657 Just (Var v) -> addBinderUnfolding env1 v con_app_unf
2658 Just (Cast (Var v) co) -> addBinderUnfolding env1 v $
2659 mkSimpleUnfolding dflags (Cast con_app (mkSymCo co))
2660 _ -> env1
2661
2662 ; traceSmpl "addAltUnf" (vcat [ppr case_bndr <+> ppr scrut, ppr con_app])
2663 ; return env2 }
2664
2665 addBinderUnfolding :: SimplEnv -> Id -> Unfolding -> SimplEnv
2666 addBinderUnfolding env bndr unf
2667 | debugIsOn, Just tmpl <- maybeUnfoldingTemplate unf
2668 = WARN( not (eqType (idType bndr) (exprType tmpl)),
2669 ppr bndr $$ ppr (idType bndr) $$ ppr tmpl $$ ppr (exprType tmpl) )
2670 modifyInScope env (bndr `setIdUnfolding` unf)
2671
2672 | otherwise
2673 = modifyInScope env (bndr `setIdUnfolding` unf)
2674
2675 zapBndrOccInfo :: Bool -> Id -> Id
2676 -- Consider case e of b { (a,b) -> ... }
2677 -- Then if we bind b to (a,b) in "...", and b is not dead,
2678 -- then we must zap the deadness info on a,b
2679 zapBndrOccInfo keep_occ_info pat_id
2680 | keep_occ_info = pat_id
2681 | otherwise = zapIdOccInfo pat_id
2682
2683 {- Note [Case binder evaluated-ness]
2684 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2685 We pin on a (OtherCon []) unfolding to the case-binder of a Case,
2686 even though it'll be over-ridden in every case alternative with a more
2687 informative unfolding. Why? Because suppose a later, less clever, pass
2688 simply replaces all occurrences of the case binder with the binder itself;
2689 then Lint may complain about the let/app invariant. Example
2690 case e of b { DEFAULT -> let v = reallyUnsafePtrEq# b y in ....
2691 ; K -> blah }
2692
2693 The let/app invariant requires that y is evaluated in the call to
2694 reallyUnsafePtrEq#, which it is. But we still want that to be true if we
2695 propagate binders to occurrences.
2696
2697 This showed up in Trac #13027.
2698
2699 Note [Add unfolding for scrutinee]
2700 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2701 In general it's unlikely that a variable scrutinee will appear
2702 in the case alternatives case x of { ...x unlikely to appear... }
2703 because the binder-swap in OccAnal has got rid of all such occcurrences
2704 See Note [Binder swap] in OccAnal.
2705
2706 BUT it is still VERY IMPORTANT to add a suitable unfolding for a
2707 variable scrutinee, in simplAlt. Here's why
2708 case x of y
2709 (a,b) -> case b of c
2710 I# v -> ...(f y)...
2711 There is no occurrence of 'b' in the (...(f y)...). But y gets
2712 the unfolding (a,b), and *that* mentions b. If f has a RULE
2713 RULE f (p, I# q) = ...
2714 we want that rule to match, so we must extend the in-scope env with a
2715 suitable unfolding for 'y'. It's *essential* for rule matching; but
2716 it's also good for case-elimintation -- suppose that 'f' was inlined
2717 and did multi-level case analysis, then we'd solve it in one
2718 simplifier sweep instead of two.
2719
2720 Exactly the same issue arises in SpecConstr;
2721 see Note [Add scrutinee to ValueEnv too] in SpecConstr
2722
2723 HOWEVER, given
2724 case x of y { Just a -> r1; Nothing -> r2 }
2725 we do not want to add the unfolding x -> y to 'x', which might seem cool,
2726 since 'y' itself has different unfoldings in r1 and r2. Reason: if we
2727 did that, we'd have to zap y's deadness info and that is a very useful
2728 piece of information.
2729
2730 So instead we add the unfolding x -> Just a, and x -> Nothing in the
2731 respective RHSs.
2732
2733
2734 ************************************************************************
2735 * *
2736 \subsection{Known constructor}
2737 * *
2738 ************************************************************************
2739
2740 We are a bit careful with occurrence info. Here's an example
2741
2742 (\x* -> case x of (a*, b) -> f a) (h v, e)
2743
2744 where the * means "occurs once". This effectively becomes
2745 case (h v, e) of (a*, b) -> f a)
2746 and then
2747 let a* = h v; b = e in f a
2748 and then
2749 f (h v)
2750
2751 All this should happen in one sweep.
2752 -}
2753
2754 knownCon :: SimplEnv
2755 -> OutExpr -- The scrutinee
2756 -> DataCon -> [OutType] -> [OutExpr] -- The scrutinee (in pieces)
2757 -> InId -> [InBndr] -> InExpr -- The alternative
2758 -> SimplCont
2759 -> SimplM (SimplEnv, OutExpr)
2760
2761 knownCon env scrut dc dc_ty_args dc_args bndr bs rhs cont
2762 = do { env' <- bind_args env bs dc_args
2763 ; env'' <- bind_case_bndr env'
2764 ; simplExprF env'' rhs cont }
2765 where
2766 zap_occ = zapBndrOccInfo (isDeadBinder bndr) -- bndr is an InId
2767
2768 -- Ugh!
2769 bind_args env' [] _ = return env'
2770
2771 bind_args env' (b:bs') (Type ty : args)
2772 = ASSERT( isTyVar b )
2773 bind_args (extendTvSubst env' b ty) bs' args
2774
2775 bind_args env' (b:bs') (Coercion co : args)
2776 = ASSERT( isCoVar b )
2777 bind_args (extendCvSubst env' b co) bs' args
2778
2779 bind_args env' (b:bs') (arg : args)
2780 = ASSERT( isId b )
2781 do { let b' = zap_occ b
2782 -- Note that the binder might be "dead", because it doesn't
2783 -- occur in the RHS; and simplNonRecX may therefore discard
2784 -- it via postInlineUnconditionally.
2785 -- Nevertheless we must keep it if the case-binder is alive,
2786 -- because it may be used in the con_app. See Note [knownCon occ info]
2787 ; env'' <- simplNonRecX env' b' arg -- arg satisfies let/app invariant
2788 ; bind_args env'' bs' args }
2789
2790 bind_args _ _ _ =
2791 pprPanic "bind_args" $ ppr dc $$ ppr bs $$ ppr dc_args $$
2792 text "scrut:" <+> ppr scrut
2793
2794 -- It's useful to bind bndr to scrut, rather than to a fresh
2795 -- binding x = Con arg1 .. argn
2796 -- because very often the scrut is a variable, so we avoid
2797 -- creating, and then subsequently eliminating, a let-binding
2798 -- BUT, if scrut is a not a variable, we must be careful
2799 -- about duplicating the arg redexes; in that case, make
2800 -- a new con-app from the args
2801 bind_case_bndr env
2802 | isDeadBinder bndr = return env
2803 | exprIsTrivial scrut = return (extendIdSubst env bndr (DoneEx scrut Nothing))
2804 | otherwise = do { dc_args <- mapM (simplVar env) bs
2805 -- dc_ty_args are aready OutTypes,
2806 -- but bs are InBndrs
2807 ; let con_app = Var (dataConWorkId dc)
2808 `mkTyApps` dc_ty_args
2809 `mkApps` dc_args
2810 ; simplNonRecX env bndr con_app }
2811
2812 -------------------
2813 missingAlt :: SimplEnv -> Id -> [InAlt] -> SimplCont -> SimplM (SimplEnv, OutExpr)
2814 -- This isn't strictly an error, although it is unusual.
2815 -- It's possible that the simplifier might "see" that
2816 -- an inner case has no accessible alternatives before
2817 -- it "sees" that the entire branch of an outer case is
2818 -- inaccessible. So we simply put an error case here instead.
2819 missingAlt env case_bndr _ cont
2820 = WARN( True, text "missingAlt" <+> ppr case_bndr )
2821 -- See Note [Avoiding space leaks in OutType]
2822 let cont_ty = contResultType cont
2823 in seqType cont_ty `seq` return (env, mkImpossibleExpr cont_ty)
2824
2825 {-
2826 ************************************************************************
2827 * *
2828 \subsection{Duplicating continuations}
2829 * *
2830 ************************************************************************
2831
2832 Consider
2833 let x* = case e of { True -> e1; False -> e2 }
2834 in b
2835 where x* is a strict binding. Then mkDupableCont will be given
2836 the continuation
2837 case [] of { True -> e1; False -> e2 } ; let x* = [] in b ; stop
2838 and will split it into
2839 dupable: case [] of { True -> $j1; False -> $j2 } ; stop
2840 join floats: $j1 = e1, $j2 = e2
2841 non_dupable: let x* = [] in b; stop
2842
2843 Putting this back togeher would give
2844 let x* = let { $j1 = e1; $j2 = e2 } in
2845 case e of { True -> $j1; False -> $j2 }
2846 in b
2847 (Of course we only do this if 'e' wants to duplicate that continuation.)
2848 Note how important it is that the new join points wrap around the
2849 inner expression, and not around the whole thing.
2850
2851 In contrast, any let-bindings introduced by mkDupableCont can wrap
2852 around the entire thing.
2853 -}
2854
2855
2856 prepareCaseCont :: SimplEnv -> [InAlt] -> SimplCont
2857 -> SimplM (SimplEnv,
2858 SimplCont, -- For the alternatives
2859 SimplCont) -- Wraps the entire case
2860 -- We are considering
2861 -- K[ case _ of { p1 -> r1; ...; pn -> rn } ]
2862 -- where K is some enclosing continuation for the case
2863 -- Goal: split K into two pieces Kdup,Knodup so that
2864 -- a) Kdup can be duplicated
2865 -- b) Knodup[Kdup[e]] = K[e]
2866 -- The idea is that we'll transform thus:
2867 -- Knodup[ (case _ of { p1 -> Kdup[r1]; ...; pn -> Kdup[rn] }
2868 --
2869 -- We may also return some extra value bindings in SimplEnv (that scope over
2870 -- the entire continuation) as well as some join points (thus must *not* float
2871 -- past the continuation!).
2872 -- Hence, the full story is this:
2873 -- K[case _ of { p1 -> r1; ...; pn -> rn }] ==>
2874 -- F_v[Knodup[F_j[ (case _ of { p1 -> Kdup[r1]; ...; pn -> Kdup[rn] }) ]]]
2875 -- Here F_v represents some values that got floated out and F_j represents some
2876 -- join points that got floated out.
2877 --
2878 -- When case-of-case is off, just make the entire continuation non-dupable
2879
2880 prepareCaseCont env alts cont
2881 | not (altsWouldDup alts)
2882 = return (env, cont, mkBoringStop (contResultType cont))
2883 | otherwise
2884 = do { (env', cont') <- mkDupableCont env cont
2885 ; return (env', cont', mkBoringStop (contResultType cont)) }
2886
2887 prepareJoinCont :: SimplEnv -> SimplCont -> SimplM (SimplEnv, SimplCont)
2888
2889 -- Similar to prepareCaseCont, only for
2890 -- K[let { j1 = r1; ...; jn -> rn } in _]
2891 -- If the js are join points, this will turn into
2892 -- Knodup[join { j1 = Kdup[r1]; ...; jn = Kdup[rn] } in Kdup[_]].
2893 --
2894 -- When case-of-case is off and it's a join binding, just make the entire
2895 -- continuation non-dupable. This is necessary because otherwise
2896 -- case (join j = ... in case e of { A -> jump j 1; ... }) of { B -> ... }
2897 -- becomes
2898 -- join j = case ... of { B -> ... } in
2899 -- case (case e of { A -> jump j 1; ... }) of { B -> ... },
2900 -- and the reference to j is invalid.
2901
2902 prepareJoinCont env cont
2903 = mkDupableCont env cont
2904
2905 altsWouldDup :: [InAlt] -> Bool -- True iff strictly > 1 non-bottom alternative
2906 altsWouldDup [] = False -- See Note [Bottom alternatives]
2907 altsWouldDup [_] = False
2908 altsWouldDup (alt:alts)
2909 | is_bot_alt alt = altsWouldDup alts
2910 | otherwise = not (all is_bot_alt alts)
2911 where
2912 is_bot_alt (_,_,rhs) = exprIsBottom rhs
2913
2914 {-
2915 Note [Bottom alternatives]
2916 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2917 When we have
2918 case (case x of { A -> error .. ; B -> e; C -> error ..)
2919 of alts
2920 then we can just duplicate those alts because the A and C cases
2921 will disappear immediately. This is more direct than creating
2922 join points and inlining them away. See Trac #4930.
2923 -}
2924
2925 -------------------------
2926 mkDupableCont :: SimplEnv -> SimplCont
2927 -> SimplM ( SimplEnv -- Incoming SimplEnv augmented with
2928 -- extra let/join-floats and in-scope variables
2929 , SimplCont) -- dup_cont: duplicable continuation
2930 mkDupableCont env cont
2931 = mk_dupable_cont env cont
2932
2933 -------------------------
2934 mk_dupable_cont :: SimplEnv -> SimplCont
2935 -> SimplM (SimplEnv, SimplCont)
2936 mk_dupable_cont env cont
2937 | contIsDupable cont
2938 = return (env, cont)
2939
2940 mk_dupable_cont _ (Stop {}) = panic "mkDupableCont" -- Handled by previous eqn
2941
2942 mk_dupable_cont env (CastIt ty cont)
2943 = do { (env', cont') <- mk_dupable_cont env cont
2944 ; return (env', CastIt ty cont') }
2945
2946 -- Duplicating ticks for now, not sure if this is good or not
2947 mk_dupable_cont env (TickIt t cont)
2948 = do { (env', cont') <- mk_dupable_cont env cont
2949 ; return (env', TickIt t cont') }
2950
2951 mk_dupable_cont env (StrictBind { sc_bndr = bndr, sc_bndrs = bndrs
2952 , sc_body = body, sc_env = se, sc_cont = cont})
2953 -- See Note [Duplicating StrictBind]
2954 = do { let sb_env = se `setInScopeAndZapFloats` env
2955 ; (sb_env1, bndr') <- simplBinder sb_env bndr
2956 ; (sb_env', join_inner) <- simplLam sb_env1 bndrs body cont
2957 -- No need to use mk_dupable_cont before simplLam; we
2958 -- use cont once here, and then share the result if necessary
2959 ; let join_body = wrapFloats sb_env' join_inner
2960 res_ty = contResultType cont
2961 ; dflags <- getDynFlags
2962 ; (env2, body2)
2963 <- if exprIsDupable dflags join_body
2964 then return (env, join_body)
2965 else do { join_bndr <- newJoinId [bndr'] res_ty
2966 ; let join_call = App (Var join_bndr) (Var bndr')
2967 join_rhs = Lam (setOneShotLambda bndr') join_body
2968 ; return (addNonRec env join_bndr join_rhs, join_call) }
2969 ; return ( env2
2970 , StrictBind { sc_bndr = bndr', sc_bndrs = []
2971 , sc_body = body2
2972 , sc_env = zapSubstEnv se
2973 , sc_dup = OkToDup
2974 , sc_cont = mkBoringStop res_ty } ) }
2975
2976 mk_dupable_cont env (StrictArg { sc_fun = info, sc_cci = cci, sc_cont = cont })
2977 -- See Note [Duplicating StrictArg]
2978 -- NB: sc_dup /= OkToDup; that is caught earlier by contIsDupable
2979 = do { (env', cont') <- mk_dupable_cont env cont
2980 ; (env'', args') <- mapAccumLM makeTrivialArg env' (ai_args info)
2981 ; return (env'', StrictArg { sc_fun = info { ai_args = args' }
2982 , sc_cci = cci
2983 , sc_cont = cont'
2984 , sc_dup = OkToDup} ) }
2985
2986 mk_dupable_cont env (ApplyToTy { sc_cont = cont
2987 , sc_arg_ty = arg_ty, sc_hole_ty = hole_ty })
2988 = do { (env', cont') <- mk_dupable_cont env cont
2989 ; return (env', ApplyToTy { sc_cont = cont'
2990 , sc_arg_ty = arg_ty, sc_hole_ty = hole_ty }) }
2991
2992 mk_dupable_cont env (ApplyToVal { sc_arg = arg, sc_dup = dup
2993 , sc_env = se, sc_cont = cont })
2994 = -- e.g. [...hole...] (...arg...)
2995 -- ==>
2996 -- let a = ...arg...
2997 -- in [...hole...] a
2998 -- NB: sc_dup /= OkToDup; that is caught earlier by contIsDupable
2999 do { (env', cont') <- mk_dupable_cont env cont
3000 ; (_, se', arg') <- simplArg env' dup se arg
3001 ; (env'', arg'') <- makeTrivial NotTopLevel env' (fsLit "karg") arg'
3002 ; return (env'', ApplyToVal { sc_arg = arg'', sc_env = se'
3003 , sc_dup = OkToDup, sc_cont = cont' }) }
3004
3005 mk_dupable_cont env (Select { sc_bndr = case_bndr, sc_alts = alts
3006 , sc_env = se, sc_cont = cont })
3007 = -- e.g. (case [...hole...] of { pi -> ei })
3008 -- ===>
3009 -- let ji = \xij -> ei
3010 -- in case [...hole...] of { pi -> ji xij }
3011 -- NB: sc_dup /= OkToDup; that is caught earlier by contIsDupable
3012 do { tick (CaseOfCase case_bndr)
3013 ; (env', alt_cont, wrap_cont) <- prepareCaseCont env alts cont
3014 -- NB: We call prepareCaseCont here. If there is only one
3015 -- alternative, then dup_cont may be big, but that's ok
3016 -- because we push it into the single alternative, and then
3017 -- use mkDupableAlt to turn that simplified alternative into
3018 -- a join point if it's too big to duplicate.
3019 -- And this is important: see Note [Fusing case continuations]
3020
3021 ; let alt_env = se `setInScopeAndZapFloats` env'
3022
3023 ; (alt_env', case_bndr') <- simplBinder alt_env case_bndr
3024 ; alts' <- mapM (simplAlt alt_env' Nothing [] case_bndr' alt_cont) alts
3025 -- Safe to say that there are no handled-cons for the DEFAULT case
3026 -- NB: simplBinder does not zap deadness occ-info, so
3027 -- a dead case_bndr' will still advertise its deadness
3028 -- This is really important because in
3029 -- case e of b { (# p,q #) -> ... }
3030 -- b is always dead, and indeed we are not allowed to bind b to (# p,q #),
3031 -- which might happen if e was an explicit unboxed pair and b wasn't marked dead.
3032 -- In the new alts we build, we have the new case binder, so it must retain
3033 -- its deadness.
3034 -- NB: we don't use alt_env further; it has the substEnv for
3035 -- the alternatives, and we don't want that
3036
3037 ; (join_binds, alts'') <- mkDupableAlts case_bndr' alts'
3038 ; let env'' = foldl (\env (j,r) -> addNonRec env j r) env' join_binds
3039
3040 ; return (env'', -- Note [Duplicated env]
3041 Select { sc_dup = OkToDup
3042 , sc_bndr = case_bndr', sc_alts = alts''
3043 , sc_env = zapSubstEnv env''
3044 , sc_cont = wrap_cont } ) }
3045
3046 mkDupableAlts :: OutId -> [OutAlt] -> SimplM ([(JoinId, OutExpr)], [OutAlt])
3047 mkDupableAlts case_bndr' the_alts
3048 = do { dflags <- getDynFlags
3049 ; (mb_join_floats, dup_alts)
3050 <- mapAndUnzipM (mkDupableAlt dflags case_bndr') the_alts
3051 ; return (catMaybes mb_join_floats, dup_alts) }
3052
3053 mkDupableAlt :: DynFlags -> OutId -> OutAlt
3054 -> SimplM (Maybe (JoinId,OutExpr), OutAlt)
3055 mkDupableAlt dflags case_bndr (con, bndrs', rhs')
3056 | exprIsDupable dflags rhs' -- Note [Small alternative rhs]
3057 = return (Nothing, (con, bndrs', rhs'))
3058
3059 | otherwise
3060 = do { let rhs_ty' = exprType rhs'
3061 scrut_ty = idType case_bndr
3062 case_bndr_w_unf
3063 = case con of
3064 DEFAULT -> case_bndr
3065 DataAlt dc -> setIdUnfolding case_bndr unf
3066 where
3067 -- See Note [Case binders and join points]
3068 unf = mkInlineUnfolding rhs
3069 rhs = mkConApp2 dc (tyConAppArgs scrut_ty) bndrs'
3070
3071 LitAlt {} -> WARN( True, text "mkDupableAlt"
3072 <+> ppr case_bndr <+> ppr con )
3073 case_bndr
3074 -- The case binder is alive but trivial, so why has
3075 -- it not been substituted away?
3076
3077 final_bndrs'
3078 | isDeadBinder case_bndr = filter abstract_over bndrs'
3079 | otherwise = bndrs' ++ [case_bndr_w_unf]
3080
3081 abstract_over bndr
3082 | isTyVar bndr = True -- Abstract over all type variables just in case
3083 | otherwise = not (isDeadBinder bndr)
3084 -- The deadness info on the new Ids is preserved by simplBinders
3085 final_args = varsToCoreExprs final_bndrs'
3086 -- Note [Join point abstraction]
3087
3088 -- We make the lambdas into one-shot-lambdas. The
3089 -- join point is sure to be applied at most once, and doing so
3090 -- prevents the body of the join point being floated out by
3091 -- the full laziness pass
3092 really_final_bndrs = map one_shot final_bndrs'
3093 one_shot v | isId v = setOneShotLambda v
3094 | otherwise = v
3095 join_rhs = mkLams really_final_bndrs rhs'
3096
3097 ; join_bndr <- newJoinId final_bndrs' rhs_ty'
3098
3099 ; let join_call = mkApps (Var join_bndr) final_args
3100 alt' = (con, bndrs', join_call)
3101
3102 ; return (Just (join_bndr, join_rhs), alt') }
3103 -- See Note [Duplicated env]
3104
3105 {-
3106 Note [Fusing case continuations]
3107 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3108 It's important to fuse two successive case continuations when the
3109 first has one alternative. That's why we call prepareCaseCont here.
3110 Consider this, which arises from thunk splitting (see Note [Thunk
3111 splitting] in WorkWrap):
3112
3113 let
3114 x* = case (case v of {pn -> rn}) of
3115 I# a -> I# a
3116 in body
3117
3118 The simplifier will find
3119 (Var v) with continuation
3120 Select (pn -> rn) (
3121 Select [I# a -> I# a] (
3122 StrictBind body Stop
3123
3124 So we'll call mkDupableCont on
3125 Select [I# a -> I# a] (StrictBind body Stop)
3126 There is just one alternative in the first Select, so we want to
3127 simplify the rhs (I# a) with continuation (StrictBind body Stop)
3128 Supposing that body is big, we end up with
3129 let $j a = <let x = I# a in body>
3130 in case v of { pn -> case rn of
3131 I# a -> $j a }
3132 This is just what we want because the rn produces a box that
3133 the case rn cancels with.
3134
3135 See Trac #4957 a fuller example.
3136
3137 Note [Case binders and join points]
3138 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3139 Consider this
3140 case (case .. ) of c {
3141 I# c# -> ....c....
3142
3143 If we make a join point with c but not c# we get
3144 $j = \c -> ....c....
3145
3146 But if later inlining scrutinises the c, thus
3147
3148 $j = \c -> ... case c of { I# y -> ... } ...
3149
3150 we won't see that 'c' has already been scrutinised. This actually
3151 happens in the 'tabulate' function in wave4main, and makes a significant
3152 difference to allocation.
3153
3154 An alternative plan is this:
3155
3156 $j = \c# -> let c = I# c# in ...c....
3157
3158 but that is bad if 'c' is *not* later scrutinised.
3159
3160 So instead we do both: we pass 'c' and 'c#' , and record in c's inlining
3161 (a stable unfolding) that it's really I# c#, thus
3162
3163 $j = \c# -> \c[=I# c#] -> ...c....
3164
3165 Absence analysis may later discard 'c'.
3166
3167 NB: take great care when doing strictness analysis;
3168 see Note [Lambda-bound unfoldings] in DmdAnal.
3169
3170 Also note that we can still end up passing stuff that isn't used. Before
3171 strictness analysis we have
3172 let $j x y c{=(x,y)} = (h c, ...)
3173 in ...
3174 After strictness analysis we see that h is strict, we end up with
3175 let $j x y c{=(x,y)} = ($wh x y, ...)
3176 and c is unused.
3177
3178 Note [Duplicated env]
3179 ~~~~~~~~~~~~~~~~~~~~~
3180 Some of the alternatives are simplified, but have not been turned into a join point
3181 So they *must* have an zapped subst-env. So we can't use completeNonRecX to
3182 bind the join point, because it might to do PostInlineUnconditionally, and
3183 we'd lose that when zapping the subst-env. We could have a per-alt subst-env,
3184 but zapping it (as we do in mkDupableCont, the Select case) is safe, and
3185 at worst delays the join-point inlining.
3186
3187 Note [Small alternative rhs]
3188 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3189 It is worth checking for a small RHS because otherwise we
3190 get extra let bindings that may cause an extra iteration of the simplifier to
3191 inline back in place. Quite often the rhs is just a variable or constructor.
3192 The Ord instance of Maybe in PrelMaybe.hs, for example, took several extra
3193 iterations because the version with the let bindings looked big, and so wasn't
3194 inlined, but after the join points had been inlined it looked smaller, and so
3195 was inlined.
3196
3197 NB: we have to check the size of rhs', not rhs.
3198 Duplicating a small InAlt might invalidate occurrence information
3199 However, if it *is* dupable, we return the *un* simplified alternative,
3200 because otherwise we'd need to pair it up with an empty subst-env....
3201 but we only have one env shared between all the alts.
3202 (Remember we must zap the subst-env before re-simplifying something).
3203 Rather than do this we simply agree to re-simplify the original (small) thing later.
3204
3205 Note [Funky mkLamTypes]
3206 ~~~~~~~~~~~~~~~~~~~~~~
3207 Notice the funky mkLamTypes. If the constructor has existentials
3208 it's possible that the join point will be abstracted over
3209 type variables as well as term variables.
3210 Example: Suppose we have
3211 data T = forall t. C [t]
3212 Then faced with
3213 case (case e of ...) of
3214 C t xs::[t] -> rhs
3215 We get the join point
3216 let j :: forall t. [t] -> ...
3217 j = /\t \xs::[t] -> rhs
3218 in
3219 case (case e of ...) of
3220 C t xs::[t] -> j t xs
3221
3222 Note [Duplicating StrictArg]
3223 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3224 We make a StrictArg duplicable simply by making all its
3225 stored-up arguments (in sc_fun) trivial, by let-binding
3226 them. Thus:
3227 f E [..hole..]
3228 ==> let a = E
3229 in f a [..hole..]
3230 Now if the thing in the hole is a case expression (which is when
3231 we'll call mkDupableCont), we'll push the function call into the
3232 branches, which is what we want. Now RULES for f may fire, and
3233 call-pattern specialisation. Here's an example from Trac #3116
3234 go (n+1) (case l of
3235 1 -> bs'
3236 _ -> Chunk p fpc (o+1) (l-1) bs')
3237 If we can push the call for 'go' inside the case, we get
3238 call-pattern specialisation for 'go', which is *crucial* for
3239 this program.
3240
3241 Here is the (&&) example:
3242 && E (case x of { T -> F; F -> T })
3243 ==> let a = E in
3244 case x of { T -> && a F; F -> && a T }
3245 Much better!
3246
3247 Notice that
3248 * Arguments to f *after* the strict one are handled by
3249 the ApplyToVal case of mkDupableCont. Eg
3250 f [..hole..] E
3251
3252 * We can only do the let-binding of E because the function
3253 part of a StrictArg continuation is an explicit syntax
3254 tree. In earlier versions we represented it as a function
3255 (CoreExpr -> CoreEpxr) which we couldn't take apart.
3256
3257 Historical aide: previously we did this (where E is a
3258 big argument:
3259 f E [..hole..]
3260 ==> let $j = \a -> f E a
3261 in $j [..hole..]
3262
3263 But this is terrible! Here's an example:
3264 && E (case x of { T -> F; F -> T })
3265 Now, && is strict so we end up simplifying the case with
3266 an ArgOf continuation. If we let-bind it, we get
3267 let $j = \v -> && E v
3268 in simplExpr (case x of { T -> F; F -> T })
3269 (ArgOf (\r -> $j r)
3270 And after simplifying more we get
3271 let $j = \v -> && E v
3272 in case x of { T -> $j F; F -> $j T }
3273 Which is a Very Bad Thing
3274
3275
3276 Note [Duplicating StrictBind]
3277 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3278 We make a StrictBind duplicable in a very similar way to
3279 that for case expressions. After all,
3280 let x* = e in b is similar to case e of x -> b
3281
3282 So we potentially make a join-point for the body, thus:
3283 let x = [] in b ==> join j x = b
3284 in let x = [] in j x
3285
3286
3287 Note [Join point abstraction] Historical note
3288 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3289 NB: This note is now historical, describing how (in the past) we used
3290 to add a void argument to nullary join points. But now that "join
3291 point" is not a fuzzy concept but a formal syntactic construct (as
3292 distinguished by the JoinId constructor of IdDetails), each of these
3293 concerns is handled separately, with no need for a vestigial extra
3294 argument.
3295
3296 Join points always have at least one value argument,
3297 for several reasons
3298
3299 * If we try to lift a primitive-typed something out
3300 for let-binding-purposes, we will *caseify* it (!),
3301 with potentially-disastrous strictness results. So
3302 instead we turn it into a function: \v -> e
3303 where v::Void#. The value passed to this function is void,
3304 which generates (almost) no code.
3305
3306 * CPR. We used to say "&& isUnliftedType rhs_ty'" here, but now
3307 we make the join point into a function whenever used_bndrs'
3308 is empty. This makes the join-point more CPR friendly.
3309 Consider: let j = if .. then I# 3 else I# 4
3310 in case .. of { A -> j; B -> j; C -> ... }
3311
3312 Now CPR doesn't w/w j because it's a thunk, so
3313 that means that the enclosing function can't w/w either,
3314 which is a lose. Here's the example that happened in practice:
3315 kgmod :: Int -> Int -> Int
3316 kgmod x y = if x > 0 && y < 0 || x < 0 && y > 0
3317 then 78
3318 else 5
3319
3320 * Let-no-escape. We want a join point to turn into a let-no-escape
3321 so that it is implemented as a jump, and one of the conditions
3322 for LNE is that it's not updatable. In CoreToStg, see
3323 Note [What is a non-escaping let]
3324
3325 * Floating. Since a join point will be entered once, no sharing is
3326 gained by floating out, but something might be lost by doing
3327 so because it might be allocated.
3328
3329 I have seen a case alternative like this:
3330 True -> \v -> ...
3331 It's a bit silly to add the realWorld dummy arg in this case, making
3332 $j = \s v -> ...
3333 True -> $j s
3334 (the \v alone is enough to make CPR happy) but I think it's rare
3335
3336 There's a slight infelicity here: we pass the overall
3337 case_bndr to all the join points if it's used in *any* RHS,
3338 because we don't know its usage in each RHS separately
3339
3340
3341
3342 ************************************************************************
3343 * *
3344 Unfoldings
3345 * *
3346 ************************************************************************
3347 -}
3348
3349 simplLetUnfolding :: SimplEnv-> TopLevelFlag
3350 -> Maybe SimplCont
3351 -> InId
3352 -> OutExpr
3353 -> Unfolding -> SimplM Unfolding
3354 simplLetUnfolding env top_lvl cont_mb id new_rhs unf
3355 | isStableUnfolding unf
3356 = simplUnfolding env top_lvl cont_mb id unf
3357 | otherwise
3358 = is_bottoming `seq` -- See Note [Force bottoming field]
3359 do { dflags <- getDynFlags
3360 ; return (mkUnfolding dflags InlineRhs is_top_lvl is_bottoming new_rhs) }
3361 -- We make an unfolding *even for loop-breakers*.
3362 -- Reason: (a) It might be useful to know that they are WHNF
3363 -- (b) In TidyPgm we currently assume that, if we want to
3364 -- expose the unfolding then indeed we *have* an unfolding
3365 -- to expose. (We could instead use the RHS, but currently
3366 -- we don't.) The simple thing is always to have one.
3367 where
3368 is_top_lvl = isTopLevel top_lvl
3369 is_bottoming = isBottomingId id
3370
3371 simplUnfolding :: SimplEnv -> TopLevelFlag
3372 -> Maybe SimplCont -- Just k => a join point with continuation k
3373 -> InId
3374 -> Unfolding -> SimplM Unfolding
3375 -- Note [Setting the new unfolding]
3376 simplUnfolding env top_lvl mb_cont id unf
3377 = case unf of
3378 NoUnfolding -> return unf
3379 BootUnfolding -> return unf
3380 OtherCon {} -> return unf
3381
3382 DFunUnfolding { df_bndrs = bndrs, df_con = con, df_args = args }
3383 -> do { (env', bndrs') <- simplBinders rule_env bndrs
3384 ; args' <- mapM (simplExpr env') args
3385 ; return (mkDFunUnfolding bndrs' con args') }
3386
3387 CoreUnfolding { uf_tmpl = expr, uf_src = src, uf_guidance = guide }
3388 | isStableSource src
3389 -> do { expr' <- case mb_cont of
3390 Just cont -> simplJoinRhs rule_env id expr cont
3391 Nothing -> simplExpr rule_env expr
3392 ; case guide of
3393 UnfWhen { ug_arity = arity, ug_unsat_ok = sat_ok } -- Happens for INLINE things
3394 -> let guide' = UnfWhen { ug_arity = arity, ug_unsat_ok = sat_ok
3395 , ug_boring_ok = inlineBoringOk expr' }
3396 -- Refresh the boring-ok flag, in case expr'
3397 -- has got small. This happens, notably in the inlinings
3398 -- for dfuns for single-method classes; see
3399 -- Note [Single-method classes] in TcInstDcls.
3400 -- A test case is Trac #4138
3401 in return (mkCoreUnfolding src is_top_lvl expr' guide')
3402 -- See Note [Top-level flag on inline rules] in CoreUnfold
3403
3404 _other -- Happens for INLINABLE things
3405 -> is_bottoming `seq` -- See Note [Force bottoming field]
3406 do { dflags <- getDynFlags
3407 ; return (mkUnfolding dflags src is_top_lvl is_bottoming expr') } }
3408 -- If the guidance is UnfIfGoodArgs, this is an INLINABLE
3409 -- unfolding, and we need to make sure the guidance is kept up
3410 -- to date with respect to any changes in the unfolding.
3411
3412 | otherwise -> return noUnfolding -- Discard unstable unfoldings
3413 where
3414 is_top_lvl = isTopLevel top_lvl
3415 is_bottoming = isBottomingId id
3416 act = idInlineActivation id
3417 rule_env = updMode (updModeForStableUnfoldings act) env
3418 -- See Note [Simplifying inside stable unfoldings] in SimplUtils
3419
3420 {-
3421 Note [Force bottoming field]
3422 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3423 We need to force bottoming, or the new unfolding holds
3424 on to the old unfolding (which is part of the id).
3425
3426 Note [Setting the new unfolding]
3427 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3428 * If there's an INLINE pragma, we simplify the RHS gently. Maybe we
3429 should do nothing at all, but simplifying gently might get rid of
3430 more crap.
3431
3432 * If not, we make an unfolding from the new RHS. But *only* for
3433 non-loop-breakers. Making loop breakers not have an unfolding at all
3434 means that we can avoid tests in exprIsConApp, for example. This is
3435 important: if exprIsConApp says 'yes' for a recursive thing, then we
3436 can get into an infinite loop
3437
3438 If there's an stable unfolding on a loop breaker (which happens for
3439 INLINABLE), we hang on to the inlining. It's pretty dodgy, but the
3440 user did say 'INLINE'. May need to revisit this choice.
3441
3442 ************************************************************************
3443 * *
3444 Rules
3445 * *
3446 ************************************************************************
3447
3448 Note [Rules in a letrec]
3449 ~~~~~~~~~~~~~~~~~~~~~~~~
3450 After creating fresh binders for the binders of a letrec, we
3451 substitute the RULES and add them back onto the binders; this is done
3452 *before* processing any of the RHSs. This is important. Manuel found
3453 cases where he really, really wanted a RULE for a recursive function
3454 to apply in that function's own right-hand side.
3455
3456 See Note [Forming Rec groups] in OccurAnal
3457 -}
3458
3459 addBndrRules :: SimplEnv -> InBndr -> OutBndr -> SimplM (SimplEnv, OutBndr)
3460 -- Rules are added back into the bin
3461 addBndrRules env in_id out_id
3462 | null old_rules
3463 = return (env, out_id)
3464 | otherwise
3465 = do { new_rules <- simplRules env (Just (idName out_id)) old_rules
3466 ; let final_id = out_id `setIdSpecialisation` mkRuleInfo new_rules
3467 ; return (modifyInScope env final_id, final_id) }
3468 where
3469 old_rules = ruleInfoRules (idSpecialisation in_id)
3470
3471 simplRules :: SimplEnv -> Maybe Name -> [CoreRule] -> SimplM [CoreRule]
3472 simplRules env mb_new_nm rules
3473 = mapM simpl_rule rules
3474 where
3475 simpl_rule rule@(BuiltinRule {})
3476 = return rule
3477
3478 simpl_rule rule@(Rule { ru_bndrs = bndrs, ru_args = args
3479 , ru_fn = fn_name, ru_rhs = rhs })
3480 = do { (env', bndrs') <- simplBinders env bndrs
3481 ; let rhs_ty = substTy env' (exprType rhs)
3482 rule_cont = mkBoringStop rhs_ty
3483 rule_env = updMode updModeForRules env'
3484 ; args' <- mapM (simplExpr rule_env) args
3485 ; rhs' <- simplExprC rule_env rhs rule_cont
3486 ; return (rule { ru_bndrs = bndrs'
3487 , ru_fn = mb_new_nm `orElse` fn_name
3488 , ru_args = args'
3489 , ru_rhs = rhs' }) }