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