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