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