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